From b1fc8c337d3b9750eff6e62b626c0bc3a1467a88 Mon Sep 17 00:00:00 2001 From: vasraz Date: Fri, 19 Mar 2021 11:25:07 +0000 Subject: Reformat catalog-be Signed-off-by: Vasyl Razinkov Issue-ID: SDC-3449 Change-Id: I45ae9fef826bcd5e3aa65c81d232d349faf02f91 --- .../sdc/be/auditing/api/AuditEventFactory.java | 1 - .../impl/AuditAuthRequestEventFactory.java | 22 +- .../be/auditing/impl/AuditBaseEventFactory.java | 39 +- .../auditing/impl/AuditConsumerEventFactory.java | 33 +- .../auditing/impl/AuditEcompOpEnvEventFactory.java | 23 +- .../impl/AuditGetUebClusterEventFactory.java | 9 +- .../sdc/be/auditing/impl/AuditingManager.java | 18 +- .../impl/category/AuditCategoryEventFactory.java | 23 +- .../AuditGetCategoryHierarchyEventFactory.java | 11 +- ...AddRemoveKeyDistributionEngineEventFactory.java | 16 +- ...tCreateTopicDistributionEngineEventFactory.java | 14 +- .../AuditDistributionDeployEventFactory.java | 29 +- .../AuditDistributionDownloadEventFactory.java | 12 +- .../AuditDistributionEngineEventFactory.java | 17 +- ...AuditDistributionEngineEventFactoryManager.java | 25 +- ...ditDistributionEngineEventMigrationFactory.java | 9 +- .../AuditDistributionNotificationEventFactory.java | 37 +- .../AuditDistributionStatusEventFactory.java | 24 +- ...uditRegUnregDistributionEngineEventFactory.java | 18 +- ...uditActivateServiceExternalApiEventFactory.java | 20 +- .../AuditAssetExternalApiEventFactory.java | 21 +- .../AuditAssetListExternalApiEventFactory.java | 19 +- ...uditChangeLifecycleExternalApiEventFactory.java | 26 +- ...AuditCreateResourceExternalApiEventFactory.java | 26 +- .../AuditCreateServiceExternalApiEventFactory.java | 24 +- .../AuditCrudExternalApiArtifactEventFactory.java | 21 +- ...ditDownloadArtifactExternalApiEventFactory.java | 14 +- .../externalapi/AuditExternalApiEventFactory.java | 13 +- .../AuditArtifactResourceAdminEventFactory.java | 28 +- ...uditCertificationResourceAdminEventFactory.java | 27 +- ...AuditCreateUpdateResourceAdminEventFactory.java | 39 +- ...tateChangeRequestResourceAdminEventFactory.java | 26 +- ...itDistStateChangeResourceAdminEventFactory.java | 31 +- .../AuditImportResourceAdminEventFactory.java | 32 +- .../AuditResourceAdminEventFactory.java | 29 +- .../AuditResourceAdminEventMigrationFactory.java | 13 +- .../AuditResourceEventFactoryManager.java | 31 +- .../usersadmin/AuditGetUsersListEventFactory.java | 14 +- .../usersadmin/AuditUserAccessEventFactory.java | 8 +- .../usersadmin/AuditUserAdminEventFactory.java | 21 +- .../sdc/be/catalog/api/IComponentMessage.java | 26 +- .../catalog/api/IMessageQueueHandlerProducer.java | 5 +- .../org/openecomp/sdc/be/catalog/api/IStatus.java | 7 +- .../openecomp/sdc/be/catalog/api/ITypeMessage.java | 2 +- .../sdc/be/catalog/enums/ChangeTypeEnum.java | 11 +- .../sdc/be/catalog/enums/ResultStatusEnum.java | 7 +- .../sdc/be/catalog/impl/ComponentMessage.java | 216 +- .../sdc/be/catalog/impl/DmaapProducer.java | 30 +- .../sdc/be/catalog/impl/DmaapProducerHealth.java | 151 +- .../sdc/be/components/ArtifactsResolver.java | 14 +- .../AttributeDeclarationOrchestrator.java | 7 +- .../components/attribute/AttributeDeclarator.java | 15 +- .../attribute/ComponentAttributeDeclarator.java | 150 +- .../ComponentInstanceAttributeDeclarator.java | 26 +- ...ComponentInstanceOutputAttributeDeclarator.java | 11 +- .../attribute/DefaultAttributeDeclarator.java | 154 +- .../be/components/attribute/GetOutputUtils.java | 5 +- .../csar/CsarArtifactsAndGroupsBusinessLogic.java | 1050 +- .../sdc/be/components/csar/CsarBusinessLogic.java | 173 +- .../openecomp/sdc/be/components/csar/CsarInfo.java | 184 +- .../csar/YamlTemplateParsingHandler.java | 371 +- .../distribution/engine/AaiRequestHandler.java | 43 +- .../distribution/engine/ArtifactInfoImpl.java | 46 +- .../distribution/engine/CambriaErrorResponse.java | 11 +- .../distribution/engine/CambriaHandler.java | 261 +- .../engine/DME2EndpointIteratorCreator.java | 5 +- .../distribution/engine/DistributionEngine.java | 111 +- .../engine/DistributionEngineClusterHealth.java | 332 +- .../engine/DistributionEngineInitTask.java | 109 +- .../engine/DistributionEnginePollingTask.java | 77 +- .../engine/DistributionNotificationSender.java | 59 +- .../engine/DistributionStatusNotification.java | 11 +- .../engine/DistributionStatusNotificationEnum.java | 6 +- .../distribution/engine/DmaapClientFactory.java | 65 +- .../distribution/engine/DmaapConsumer.java | 41 +- .../distribution/engine/DmaapHealth.java | 216 +- .../engine/DmaapNotificationDataImpl.java | 7 +- .../engine/EnvironmentMessageBusData.java | 13 +- .../distribution/engine/EnvironmentsEngine.java | 219 +- .../distribution/engine/ExecutorFactory.java | 27 +- .../distribution/engine/IArtifactInfo.java | 19 +- .../distribution/engine/ICambriaHandler.java | 31 +- .../distribution/engine/IDistributionEngine.java | 1 - .../engine/IDmaapAuditNotificationData.java | 7 +- .../engine/IDmaapNotificationData.java | 24 +- .../distribution/engine/INotificationData.java | 85 +- .../distribution/engine/INotificationHandler.java | 8 +- .../distribution/engine/IResourceArtifactInfo.java | 14 +- .../distribution/engine/IServiceArtifactInfo.java | 5 +- .../engine/JsonContainerResourceInstance.java | 21 +- .../distribution/engine/NotificationDataImpl.java | 56 +- .../engine/NotificationExecutorService.java | 17 +- .../engine/ResourceArtifactInfoImpl.java | 9 +- .../engine/ServiceArtifactInfoImpl.java | 6 +- .../ServiceDistributionArtifactsBuilder.java | 148 +- .../distribution/engine/SubscriberTypeEnum.java | 6 +- .../distribution/engine/UebHealthCheckCall.java | 34 +- .../engine/VfModuleArtifactPayload.java | 58 +- .../config/DistributionEngineSpringConfig.java | 8 +- .../report/DistributionCompleteReporter.java | 6 +- .../report/MsoDistributionCompleteReporter.java | 11 +- .../engine/rest/DistributionStatusRequest.java | 5 +- .../distribution/engine/rest/MSORestClient.java | 33 +- .../health/HealthCheckBusinessLogic.java | 138 +- .../health/PortalHealthCheckBuilder.java | 78 +- .../impl/AbstractTemplateBusinessLogic.java | 91 +- .../impl/ActivationRequestInformation.java | 6 +- .../impl/AdditionalInformationBusinessLogic.java | 227 +- .../components/impl/AnnotationBusinessLogic.java | 33 +- .../be/components/impl/ArchiveBusinessLogic.java | 116 +- .../be/components/impl/ArtifactResolverImpl.java | 40 +- .../be/components/impl/ArtifactsBusinessLogic.java | 2280 ++-- .../be/components/impl/AttributeBusinessLogic.java | 202 +- .../sdc/be/components/impl/BaseBusinessLogic.java | 185 +- .../sdc/be/components/impl/CADIHealthCheck.java | 27 +- .../components/impl/CapabilitiesBusinessLogic.java | 378 +- .../impl/CapabilityTypeImportManager.java | 41 +- .../be/components/impl/CassandraHealthCheck.java | 68 +- .../components/impl/CategoriesImportManager.java | 117 +- .../be/components/impl/CommonImportManager.java | 258 +- .../be/components/impl/ComponentBusinessLogic.java | 517 +- .../impl/ComponentBusinessLogicProvider.java | 10 +- .../impl/ComponentInstanceBusinessLogic.java | 1548 ++- .../ComponentInterfaceOperationBusinessLogic.java | 95 +- .../sdc/be/components/impl/ComponentLocker.java | 10 +- .../impl/ComponentNodeFilterBusinessLogic.java | 225 +- .../ComponentSubstitutionFilterBusinessLogic.java | 126 +- .../components/impl/CompositionBusinessLogic.java | 263 +- .../be/components/impl/ConsumerBusinessLogic.java | 47 +- .../be/components/impl/CsarValidationUtils.java | 176 +- .../be/components/impl/DataTypeBusinessLogic.java | 42 +- .../be/components/impl/DataTypeImportManager.java | 96 +- .../sdc/be/components/impl/DataTypesService.java | 15 +- .../impl/DistributionMonitoringBusinessLogic.java | 66 +- .../be/components/impl/ElementBusinessLogic.java | 539 +- .../components/impl/ExternalRefsBusinessLogic.java | 54 +- .../impl/GenericArtifactBrowserBusinessLogic.java | 35 +- .../sdc/be/components/impl/GroupBusinessLogic.java | 616 +- .../be/components/impl/GroupBusinessLogicNew.java | 120 +- .../be/components/impl/GroupTypeBusinessLogic.java | 22 +- .../be/components/impl/GroupTypeImportManager.java | 86 +- .../be/components/impl/HealthCheckInformer.java | 5 +- .../impl/IDeploymentArtifactTypeConfigGetter.java | 6 +- .../sdc/be/components/impl/ImportUtils.java | 362 +- .../be/components/impl/InputsBusinessLogic.java | 427 +- .../impl/InterfaceDefinitionHandler.java | 90 +- .../impl/InterfaceLifecycleTypeImportManager.java | 39 +- .../impl/InterfaceOperationBusinessLogic.java | 448 +- .../components/impl/NodeFilterUploadCreator.java | 23 +- .../components/impl/OnDeleteEntityOperation.java | 9 +- .../be/components/impl/OutputsBusinessLogic.java | 80 +- .../be/components/impl/PolicyBusinessLogic.java | 313 +- .../components/impl/PolicyTypeBusinessLogic.java | 26 +- .../components/impl/PolicyTypeImportManager.java | 71 +- .../be/components/impl/ProductBusinessLogic.java | 245 +- .../be/components/impl/PropertyBusinessLogic.java | 286 +- .../impl/RelationshipTypeBusinessLogic.java | 25 +- .../impl/RelationshipTypeImportManager.java | 65 +- .../components/impl/RequirementBusinessLogic.java | 359 +- .../components/impl/RequirementsBusinessLogic.java | 10 +- .../be/components/impl/ResourceBusinessLogic.java | 10425 +++++++++---------- .../be/components/impl/ResourceImportManager.java | 393 +- .../be/components/impl/ResponseFormatManager.java | 7 +- .../be/components/impl/ServiceBusinessLogic.java | 1245 +-- .../impl/ServiceImportBusinessLogic.java | 1336 +-- .../be/components/impl/ServiceImportManager.java | 117 +- .../components/impl/ServiceImportParseLogic.java | 1025 +- .../impl/SoftwareInformationBusinessLogic.java | 57 +- .../be/components/impl/TogglingBusinessLogic.java | 18 +- .../sdc/be/components/impl/aaf/AafPermission.java | 25 +- .../sdc/be/components/impl/aaf/AafRoles.java | 21 +- .../be/components/impl/aaf/PermissionAllowed.java | 2 +- .../impl/aaf/RoleAuthorizationHandler.java | 16 +- .../impl/artifact/ArtifactOperationInfo.java | 4 +- .../ArtifactTypeToPayloadTypeSelector.java | 22 +- .../components/impl/artifact/PayloadTypeEnum.java | 45 +- .../impl/exceptions/BusinessLogicException.java | 2 - .../ByActionStatusComponentException.java | 9 +- .../ByResponseFormatComponentException.java | 7 +- .../impl/exceptions/ComponentException.java | 16 +- .../exceptions/SdcResourceNotFoundException.java | 16 +- .../impl/generic/GenericTypeBusinessLogic.java | 41 +- .../components/impl/group/GroupMembersUpdater.java | 18 +- .../components/impl/group/GroupVersionUpdater.java | 90 +- ...mponentInstanceChangeOperationOrchestrator.java | 27 +- .../impl/instance/GroupMembersUpdateOperation.java | 24 +- .../impl/instance/OnChangeVersionOperation.java | 12 +- .../OnComponentInstanceChangeOperation.java | 6 +- .../instance/PolicyTargetsUpdateOperation.java | 13 +- .../components/impl/lock/ComponentLockAspect.java | 10 +- .../components/impl/lock/LockingTransactional.java | 8 +- .../components/impl/model/ToscaTypeImportData.java | 8 +- .../impl/policy/PolicyTargetsUpdateHandler.java | 24 +- .../impl/policy/PolicyTargetsUpdater.java | 26 +- .../impl/policy/PolicyVersionUpdater.java | 32 +- .../components/impl/utils/CINodeFilterUtils.java | 40 +- .../impl/utils/CapabilityTypeImportUtils.java | 22 +- .../be/components/impl/utils/ComponentUtils.java | 53 +- .../impl/utils/CreateServiceFromYamlParameter.java | 6 +- .../be/components/impl/utils/DirectivesUtil.java | 6 +- .../be/components/impl/utils/ExceptionUtils.java | 16 +- .../impl/utils/PolicyTypeImportUtils.java | 55 +- .../impl/validation/PMDictionaryValidator.java | 13 +- .../impl/version/OnChangeVersionCommand.java | 10 +- .../impl/version/VesionUpdateHandler.java | 34 +- .../lifecycle/CertificationChangeTransition.java | 154 +- .../be/components/lifecycle/CheckinTransition.java | 63 +- .../components/lifecycle/CheckoutTransition.java | 66 +- .../components/lifecycle/LifeCycleTransition.java | 66 +- .../lifecycle/LifecycleBusinessLogic.java | 294 +- .../lifecycle/LifecycleChangeInfoBase.java | 11 +- .../lifecycle/LifecycleChangeInfoWithAction.java | 11 +- .../lifecycle/UndoCheckoutTransition.java | 57 +- .../merge/ComponentsGlobalMergeCommand.java | 6 +- .../components/merge/ComponentsMergeCommand.java | 10 +- .../merge/GlobalInputsFilteringBusinessLogic.java | 23 +- .../be/components/merge/RelationsComparator.java | 55 +- .../be/components/merge/TopologyComparator.java | 42 +- .../merge/VspComponentsMergeCommand.java | 6 +- .../merge/capability/CapabilityResolver.java | 23 +- .../merge/capability/SimpleCapabilityResolver.java | 67 +- .../merge/group/ComponentGroupMergeCommand.java | 54 +- .../merge/group/GroupPropertiesMergeCommand.java | 60 +- .../heat/HeatEnvArtifactsMergeBusinessLogic.java | 42 +- .../merge/input/ComponentInputsMergeBL.java | 36 +- .../merge/input/DeclaredInputsResolver.java | 62 +- .../merge/input/GlobalInputsMergeCommand.java | 35 +- .../components/merge/input/InputsMergeCommand.java | 42 +- .../input/InputsValuesMergingBusinessLogic.java | 22 +- .../ComponentCapabilitiesPropertiesMergeBL.java | 43 +- .../instance/ComponentInstanceArtifactsMerge.java | 106 +- ...mponentInstanceCapabilitiesPropertiesMerge.java | 34 +- .../ComponentInstanceForwardingPathMerge.java | 49 +- .../instance/ComponentInstanceHeatEnvMerge.java | 34 +- .../instance/ComponentInstanceInputsMergeBL.java | 52 +- .../ComponentInstanceInputsRedeclareHandler.java | 66 +- .../instance/ComponentInstanceInterfacesMerge.java | 50 +- .../ComponentInstanceMergeDataBusinessLogic.java | 25 +- .../instance/ComponentInstanceMergeInterface.java | 8 +- .../ComponentInstancePropertiesMergeBL.java | 65 +- .../ComponentInstancePropsAndInputsMerge.java | 56 +- .../instance/ComponentInstanceRelationMerge.java | 141 +- .../ComponentInstanceRelationMergeCommand.java | 17 +- .../instance/ContainerRelationsMergeInfo.java | 7 +- .../merge/instance/DataForMergeHolder.java | 44 +- .../merge/instance/ExternalRefsMergeBL.java | 28 +- .../merge/instance/RelationMergeInfo.java | 2 - .../merge/policy/PoliciesMergeCommand.java | 66 +- .../DataDefinitionsValuesMergingBusinessLogic.java | 43 +- .../merge/property/MergePropertyData.java | 23 +- .../PropertyDataValueMergeBusinessLogic.java | 54 +- .../property/PropertyInstanceMergeDataBuilder.java | 57 +- .../merge/property/PropertyValueMerger.java | 93 +- .../merge/resource/MergeCommandsFactory.java | 17 +- .../merge/resource/MergeResourceBusinessLogic.java | 6 +- .../resource/ResourceDataMergeBusinessLogic.java | 21 +- .../be/components/merge/utils/CapabilityOwner.java | 10 +- .../utils/ComponentInstanceBuildingBlocks.java | 32 +- .../components/merge/utils/MergeInstanceUtils.java | 366 +- .../components/path/ForwardingPathValidator.java | 72 +- .../ComponentInstanceInputPropertyDeclarator.java | 62 +- .../ComponentInstancePropertyDeclarator.java | 74 +- .../property/ComponentPropertyDeclarator.java | 270 +- .../property/DefaultPropertyDeclarator.java | 426 +- .../sdc/be/components/property/GetInputUtils.java | 8 +- .../property/GroupPropertyDeclarator.java | 52 +- .../property/PolicyPropertyDeclarator.java | 49 +- .../property/PropertyConstraintsUtils.java | 42 +- .../property/PropertyDeclarationOrchestrator.java | 114 +- .../be/components/property/PropertyDeclarator.java | 56 +- ...omponentInstancePropertyToPolicyDeclarator.java | 42 +- .../ComponentPropertyToPolicyDeclarator.java | 71 +- .../scheduledtasks/AbstractScheduleTaskRunner.java | 22 +- .../scheduledtasks/AsdcComponentsCleanerTask.java | 67 +- .../ComponentsCleanBusinessLogic.java | 46 +- .../scheduledtasks/RecoveryThreadManager.java | 106 +- .../sdc/be/components/upgrade/ServiceInfo.java | 73 +- .../components/upgrade/UpgradeBusinessLogic.java | 240 +- .../sdc/be/components/upgrade/UpgradeRequest.java | 24 +- .../sdc/be/components/upgrade/UpgradeStatus.java | 20 +- .../sdc/be/components/utils/ArtifactUtils.java | 1 - .../sdc/be/components/utils/ConsumptionUtils.java | 54 +- .../components/utils/InterfaceOperationUtils.java | 105 +- .../sdc/be/components/utils/MapUtils.java | 132 +- .../sdc/be/components/utils/PropertiesUtils.java | 134 +- .../openecomp/sdc/be/components/utils/Utils.java | 26 +- .../components/validation/AccessValidations.java | 18 +- .../components/validation/AnnotationValidator.java | 36 +- .../be/components/validation/ApiResourceEnum.java | 11 +- .../validation/CapabilitiesValidation.java | 147 +- .../validation/ComponentValidations.java | 57 +- .../validation/InterfaceOperationValidation.java | 430 +- .../components/validation/NodeFilterValidator.java | 247 +- .../sdc/be/components/validation/PolicyUtils.java | 96 +- .../components/validation/PropertyValidator.java | 91 +- .../validation/RequirementValidation.java | 186 +- .../validation/ServiceDistributionValidation.java | 40 +- .../be/components/validation/UserValidations.java | 67 +- .../components/validation/ValidationException.java | 6 +- .../be/components/validation/ValidationUtils.java | 8 +- .../component/ComponentContactIdValidator.java | 5 +- .../component/ComponentDescriptionValidator.java | 15 +- .../component/ComponentFieldValidator.java | 2 - .../component/ComponentIconValidator.java | 20 +- .../component/ComponentNameValidator.java | 25 +- .../component/ComponentProjectCodeValidator.java | 9 +- .../component/ComponentTagsValidator.java | 22 +- .../validation/component/ComponentValidator.java | 8 +- .../service/ServiceCategoryValidator.java | 21 +- .../ServiceEnvironmentContextValidator.java | 16 +- .../validation/service/ServiceFieldValidator.java | 3 +- .../service/ServiceFunctionValidator.java | 6 +- .../service/ServiceInstantiationTypeValidator.java | 4 +- .../service/ServiceNamingPolicyValidator.java | 5 +- .../validation/service/ServiceRoleValidator.java | 14 +- .../validation/service/ServiceTypeValidator.java | 3 +- .../validation/service/ServiceValidator.java | 10 +- .../sdc/be/datamodel/ForwardingPaths.java | 24 +- .../org/openecomp/sdc/be/datamodel/NameIdPair.java | 24 +- .../sdc/be/datamodel/NameIdPairWrapper.java | 13 +- .../sdc/be/datamodel/ServiceRelations.java | 5 +- .../sdc/be/datamodel/api/CategoryTypeEnum.java | 8 +- .../sdc/be/datamodel/api/HighestFilterEnum.java | 7 +- .../sdc/be/datamodel/utils/ArtifactUtils.java | 70 +- .../be/datamodel/utils/ConstraintConvertor.java | 21 +- .../be/datamodel/utils/NodeTypeConvertUtils.java | 74 +- .../PropertyValueConstraintValidationUtil.java | 216 +- .../datamodel/utils/UiComponentDataConverter.java | 120 +- .../sdc/be/distribution/AuditHandler.java | 33 +- .../be/distribution/DistributionBusinessLogic.java | 220 +- .../api/client/CambriaOperationStatus.java | 7 +- .../api/client/RegistrationRequest.java | 9 +- .../api/client/ServerListResponse.java | 6 +- .../api/client/TopicRegistrationResponse.java | 6 +- .../api/client/TopicUnregistrationResponse.java | 9 +- .../servlet/DistributionCatalogServlet.java | 221 +- .../distribution/servlet/DistributionServlet.java | 252 +- .../org/openecomp/sdc/be/dto/ExternalRefDTO.java | 7 +- .../org/openecomp/sdc/be/ecomp/EcompIntImpl.java | 99 +- .../sdc/be/ecomp/PortalPropertiesEnum.java | 10 +- .../be/ecomp/PortalRestApiCentralServiceImpl.java | 89 +- .../ecomp/converters/AssetMetadataConverter.java | 187 +- .../be/ecomp/converters/EcompRoleConverter.java | 12 +- .../be/ecomp/converters/EcompUserConverter.java | 15 - .../RestrictionAccessFilterException.java | 6 +- .../sdc/be/exception/SdcActionException.java | 5 +- .../sdc/be/exception/ToscaExportException.java | 2 - .../servlet/AbstractTemplateServlet.java | 176 +- .../servlet/ArtifactExternalServlet.java | 769 +- .../be/externalapi/servlet/AssetsDataServlet.java | 261 +- .../externalapi/servlet/CrudExternalServlet.java | 418 +- .../externalapi/servlet/ExternalRefsServlet.java | 150 +- .../servlet/ServiceActivationServlet.java | 94 +- .../representation/AbstractResourceInfo.java | 4 +- .../servlet/representation/ArtifactMetadata.java | 6 +- .../servlet/representation/AssetMetadata.java | 6 +- .../servlet/representation/CopyServiceInfo.java | 3 +- .../servlet/representation/IAssetMetadata.java | 6 +- .../representation/ProductAssetMetadata.java | 6 +- .../ProductCategoryGroupMetadata.java | 6 +- .../servlet/representation/ReplaceVNFInfo.java | 9 +- .../ResourceAssetDetailedMetadata.java | 5 +- .../representation/ResourceAssetMetadata.java | 6 +- .../representation/ResourceInstanceMetadata.java | 6 +- .../ServiceAssetDetailedMetadata.java | 6 +- .../representation/ServiceAssetMetadata.java | 6 +- .../representation/ServiceDistributionReqInfo.java | 6 +- .../ServiceDistributionRespInfo.java | 6 +- .../sdc/be/facade/operations/CatalogOperation.java | 54 +- .../be/facade/operations/FacadeOperationUtils.java | 8 +- .../sdc/be/facade/operations/UserOperation.java | 27 +- .../sdc/be/filters/BasicAuthenticationFilter.java | 92 +- .../sdc/be/filters/BeCadiServletFilter.java | 59 +- .../sdc/be/filters/BeRestrictionAccessFilter.java | 18 +- .../openecomp/sdc/be/filters/BeServletFilter.java | 43 +- .../be/filters/ComponentsAvailabilityFilter.java | 76 +- .../sdc/be/filters/FilterConfiguration.java | 4 +- .../openecomp/sdc/be/filters/GatewayFilter.java | 37 +- .../sdc/be/filters/PortalConfiguration.java | 18 +- .../sdc/be/filters/ReqValidationFilter.java | 32 +- .../openecomp/sdc/be/filters/ThreadLocalUtils.java | 28 +- .../org/openecomp/sdc/be/impl/ComponentsUtils.java | 756 +- .../openecomp/sdc/be/impl/ForwardingPathUtils.java | 159 +- .../openecomp/sdc/be/impl/ServiceFilterUtils.java | 75 +- .../org/openecomp/sdc/be/impl/ServletUtils.java | 11 +- .../sdc/be/impl/WebAppContextWrapper.java | 10 +- .../sdc/be/info/ArtifactDefinitionInfo.java | 10 +- .../sdc/be/info/ArtifactTemplateInfo.java | 181 +- .../openecomp/sdc/be/info/ArtifactTypesInfo.java | 9 +- .../sdc/be/info/CreateAndAssotiateInfo.java | 6 +- .../openecomp/sdc/be/info/DistributionStatus.java | 16 +- .../sdc/be/info/DistributionStatusInfo.java | 5 +- .../be/info/DistributionStatusListResponse.java | 6 +- .../be/info/DistributionStatusOfServiceInfo.java | 6 +- .../DistributionStatusOfServiceListResponce.java | 6 +- .../sdc/be/info/GenericArtifactQueryInfo.java | 2 +- .../openecomp/sdc/be/info/GroupDefinitionInfo.java | 36 +- .../openecomp/sdc/be/info/GroupTemplateInfo.java | 6 +- .../openecomp/sdc/be/info/MergedArtifactInfo.java | 56 +- .../sdc/be/info/NodeTypeInfoToUpdateArtifacts.java | 8 +- .../openecomp/sdc/be/info/OperationalEnvInfo.java | 33 +- .../openecomp/sdc/be/info/RelatedToProperty.java | 6 +- .../org/openecomp/sdc/be/info/Relationship.java | 20 +- .../openecomp/sdc/be/info/RelationshipData.java | 1 - .../openecomp/sdc/be/info/RelationshipList.java | 8 +- .../org/openecomp/sdc/be/info/ServiceInfo.java | 6 +- .../openecomp/sdc/be/info/ServiceVersionInfo.java | 21 +- .../org/openecomp/sdc/be/info/ServicesWrapper.java | 6 +- .../openecomp/sdc/be/info/ServletJsonResponse.java | 6 +- .../openecomp/sdc/be/info/ToscaNodeTypeInfo.java | 8 +- .../sdc/be/info/ToscaNodeTypeInterface.java | 6 +- .../sdc/be/listen/BEAppContextListener.java | 31 +- .../sdc/be/mixin/ComponentInstanceInputMixin.java | 11 +- .../be/mixin/ComponentInstancePropertyMixin.java | 8 +- .../sdc/be/mixin/GroupCompositionMixin.java | 16 +- .../org/openecomp/sdc/be/mixin/GroupTypeMixin.java | 12 +- .../sdc/be/mixin/InputDefinitionMixin.java | 5 +- .../sdc/be/mixin/PolicyCompositionMixin.java | 21 +- .../openecomp/sdc/be/mixin/PolicyTypeMixin.java | 12 +- .../sdc/be/mixin/PropertyDefinitionMixin.java | 23 +- .../sdc/be/plugins/CsarEntryGenerator.java | 22 +- .../sdc/be/plugins/ServiceCreationPlugin.java | 2 - .../be/servlets/AbstractValidationsServlet.java | 436 +- .../be/servlets/AdditionalInformationServlet.java | 386 +- .../openecomp/sdc/be/servlets/ArchiveEndpoint.java | 175 +- .../openecomp/sdc/be/servlets/ArtifactServlet.java | 627 +- .../sdc/be/servlets/AttributeServlet.java | 100 +- .../sdc/be/servlets/AutomatedUpgradeEndpoint.java | 80 +- .../sdc/be/servlets/BeGenericServlet.java | 163 +- .../sdc/be/servlets/BeMonitoringServlet.java | 49 +- .../sdc/be/servlets/CapabilityServlet.java | 280 +- .../sdc/be/servlets/ComponentAttributeServlet.java | 52 +- .../sdc/be/servlets/ComponentInstanceServlet.java | 1234 +-- .../ComponentInterfaceOperationServlet.java | 61 +- .../be/servlets/ComponentNodeFilterServlet.java | 157 +- .../sdc/be/servlets/ComponentPropertyServlet.java | 584 +- .../sdc/be/servlets/ComponentServlet.java | 302 +- .../ComponentSubstitutionFilterServlet.java | 151 +- .../sdc/be/servlets/ConfigMgrServlet.java | 40 +- .../openecomp/sdc/be/servlets/ConfigServlet.java | 32 +- .../openecomp/sdc/be/servlets/ConsumerServlet.java | 106 +- .../sdc/be/servlets/DirectiveServlet.java | 18 +- .../be/servlets/DistributionServiceServlet.java | 81 +- .../openecomp/sdc/be/servlets/ElementServlet.java | 413 +- .../sdc/be/servlets/ExceptionHandlerEndpoint.java | 21 +- .../be/servlets/GenericArtifactBrowserServlet.java | 52 +- .../openecomp/sdc/be/servlets/GroupEndpoint.java | 78 +- .../openecomp/sdc/be/servlets/GroupServlet.java | 129 +- .../sdc/be/servlets/GroupTypesEndpoint.java | 41 +- .../openecomp/sdc/be/servlets/InputsServlet.java | 405 +- .../sdc/be/servlets/InterfaceOperationServlet.java | 287 +- .../sdc/be/servlets/LifecycleServlet.java | 76 +- .../openecomp/sdc/be/servlets/OutputsServlet.java | 75 +- .../openecomp/sdc/be/servlets/PolicyServlet.java | 353 +- .../sdc/be/servlets/PolicyTypesEndpoint.java | 44 +- .../sdc/be/servlets/RepresentationUtils.java | 76 +- .../sdc/be/servlets/RequirementServlet.java | 281 +- .../sdc/be/servlets/ResourceUploadServlet.java | 169 +- .../sdc/be/servlets/ResourcesServlet.java | 305 +- .../sdc/be/servlets/ServiceConsumptionServlet.java | 327 +- .../be/servlets/ServiceForwardingPathServlet.java | 168 +- .../openecomp/sdc/be/servlets/ServiceServlet.java | 464 +- .../sdc/be/servlets/ServiceUploadServlet.java | 60 +- .../openecomp/sdc/be/servlets/TogglingServlet.java | 62 +- .../sdc/be/servlets/TypesFetchServlet.java | 206 +- .../sdc/be/servlets/TypesUploadEndpoint.java | 87 +- .../sdc/be/servlets/TypesUploadServlet.java | 277 +- .../sdc/be/servlets/UserAdminServlet.java | 224 +- .../exception/ComponentExceptionMapper.java | 25 +- .../ConstraintViolationExceptionMapper.java | 14 +- .../servlets/exception/DefaultExceptionMapper.java | 16 +- .../PropertyConstraintExceptionMapper.java | 16 +- .../servlets/exception/StorageExceptionMapper.java | 20 +- .../be/switchover/detector/SwitchoverDetector.java | 188 +- .../be/togglz/CassandraCustomStateRepository.java | 20 +- .../openecomp/sdc/be/tosca/AttributeConverter.java | 34 +- .../be/tosca/CapabilityRequirementConverter.java | 300 +- .../org/openecomp/sdc/be/tosca/ComponentCache.java | 101 +- .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 1376 ++- .../org/openecomp/sdc/be/tosca/FJToVavrHelper.java | 10 +- .../openecomp/sdc/be/tosca/GroupExportParser.java | 15 +- .../sdc/be/tosca/GroupExportParserImpl.java | 409 +- .../be/tosca/InterfacesOperationsConverter.java | 291 +- .../openecomp/sdc/be/tosca/PolicyExportParser.java | 10 +- .../sdc/be/tosca/PolicyExportParserImpl.java | 316 +- .../openecomp/sdc/be/tosca/PropertyConvertor.java | 63 +- .../org/openecomp/sdc/be/tosca/ToscaError.java | 6 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 611 +- .../ToscaExportRelationshipTemplatesHandler.java | 34 +- .../sdc/be/tosca/ToscaRepresentation.java | 9 +- .../org/openecomp/sdc/be/tosca/ToscaUtils.java | 39 +- .../java/org/openecomp/sdc/be/tosca/ZipWriter.java | 34 +- .../be/tosca/builder/ToscaRelationshipBuilder.java | 3 - .../tosca/exception/ToscaConversionException.java | 1 - .../sdc/be/tosca/model/CapabilityFilter.java | 10 +- .../sdc/be/tosca/model/IToscaMetadata.java | 5 +- .../openecomp/sdc/be/tosca/model/NodeFilter.java | 3 +- .../sdc/be/tosca/model/SubstitutionMapping.java | 1 - .../sdc/be/tosca/model/ToscaAnnotation.java | 34 +- .../sdc/be/tosca/model/ToscaAttribute.java | 3 - .../sdc/be/tosca/model/ToscaCapability.java | 15 +- .../sdc/be/tosca/model/ToscaDataType.java | 5 +- .../sdc/be/tosca/model/ToscaGroupTemplate.java | 50 +- .../openecomp/sdc/be/tosca/model/ToscaInput.java | 18 +- .../be/tosca/model/ToscaInterfaceDefinition.java | 2 - .../sdc/be/tosca/model/ToscaInterfaceNodeType.java | 74 +- .../model/ToscaLifecycleOperationDefinition.java | 5 - .../sdc/be/tosca/model/ToscaMetadata.java | 23 +- .../sdc/be/tosca/model/ToscaNodeTemplate.java | 9 +- .../sdc/be/tosca/model/ToscaNodeType.java | 4 - .../be/tosca/model/ToscaOperationAssignment.java | 2 - .../openecomp/sdc/be/tosca/model/ToscaOutput.java | 2 - .../sdc/be/tosca/model/ToscaPolicyTemplate.java | 37 +- .../sdc/be/tosca/model/ToscaProperty.java | 2 - .../be/tosca/model/ToscaPropertyAssignment.java | 2 - .../be/tosca/model/ToscaPropertyConstraint.java | 2 - .../model/ToscaPropertyConstraintValidValues.java | 2 - .../sdc/be/tosca/model/ToscaRelationship.java | 1 - .../be/tosca/model/ToscaRelationshipTemplate.java | 1 - .../sdc/be/tosca/model/ToscaRequirement.java | 6 +- .../sdc/be/tosca/model/ToscaSchemaDefinition.java | 6 +- .../sdc/be/tosca/model/ToscaTemplate.java | 3 - .../sdc/be/tosca/model/ToscaTemplateArtifact.java | 6 +- .../be/tosca/model/ToscaTemplateCapability.java | 7 +- .../be/tosca/model/ToscaTemplateRequirement.java | 18 +- .../sdc/be/tosca/model/ToscaTopolgyTemplate.java | 1 - .../sdc/be/tosca/model/VfModuleToscaMetadata.java | 6 +- .../be/tosca/utils/ForwardingPathToscaUtil.java | 92 +- .../sdc/be/tosca/utils/InputConverter.java | 26 +- .../sdc/be/tosca/utils/InterfaceTypesNameUtil.java | 7 +- .../sdc/be/tosca/utils/NodeFilterConverter.java | 34 +- .../sdc/be/tosca/utils/OperationArtifactUtil.java | 59 +- .../sdc/be/tosca/utils/OutputConverter.java | 8 +- .../tosca/utils/SubstitutionFilterConverter.java | 39 +- .../sdc/be/types/ServiceConsumptionData.java | 74 +- .../sdc/be/types/ServiceConsumptionSource.java | 40 +- .../main/java/org/openecomp/sdc/be/user/Role.java | 9 +- .../org/openecomp/sdc/be/user/UserAdminAction.java | 7 +- .../openecomp/sdc/be/user/UserAdminValidator.java | 22 +- .../openecomp/sdc/be/user/UserBusinessLogic.java | 78 +- .../sdc/be/user/UserBusinessLogicExt.java | 33 +- .../org/openecomp/sdc/be/user/UserMessage.java | 2 +- .../openecomp/sdc/be/user/UserOperationEnum.java | 1 - .../main/java/org/openecomp/sdc/be/view/Mixin.java | 6 +- .../openecomp/sdc/be/view/MixinModelWriter.java | 39 +- .../openecomp/sdc/be/view/MixinSourceTarget.java | 5 +- .../org/openecomp/sdc/be/view/MixinTarget.java | 8 +- .../org/openecomp/sdc/be/view/ResponseView.java | 11 +- .../sdc/config/CatalogBESpringConfig.java | 27 +- .../openecomp/sdc/config/HttpClientFactory.java | 35 +- .../openecomp/sdc/config/ObjectMapperProvider.java | 7 +- .../sdc/externalupload/utils/ServiceUtils.java | 103 +- 552 files changed, 25366 insertions(+), 35373 deletions(-) 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 index 541fea815a..3359285d99 100644 --- 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.api; import java.util.List; 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 index e3d43137bf..66f67c3b42 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -27,7 +26,7 @@ import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; public class AuditAuthRequestEventFactory extends AuditBaseEventFactory { - private static final String LOG_STR = "ACTION = \"%s\" URL = \"%s\" USER = \"%s\" AUTH_STATUS = \"%s\" REALM = \"%s\""; + private static final String LOG_STR = "ACTION = \"%s\" URL = \"%s\" USER = \"%s\" AUTH_STATUS = \"%s\" REALM = \"%s\""; private final AuthEvent event; public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm, String authStatus) { @@ -35,10 +34,10 @@ public class AuditAuthRequestEventFactory extends AuditBaseEventFactory { event = new AuthEvent(getAction().getName(), commonFields, authUser, authUrl, realm, authStatus); } - public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm, - String authStatus, String timestamp) { - this(commonFields, authUser, authUrl, realm, authStatus); - this.event.setTimestamp1(timestamp); + public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm, String authStatus, + String timestamp) { + this(commonFields, authUser, authUrl, realm, authStatus); + this.event.setTimestamp1(timestamp); } @Override @@ -48,10 +47,11 @@ public class AuditAuthRequestEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getUrl(), event.getUser(), - event.getAuthStatus(), event.getRealm()}; + return new String[]{event.getAction(), event.getUrl(), event.getUser(), event.getAuthStatus(), event.getRealm()}; } @Override - public AuditingGenericEvent getDbEvent() { return event; } + 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 index 91212ad11e..986b60bdc8 100644 --- 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 @@ -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. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; import org.apache.commons.lang.StringUtils; import org.javatuples.Pair; import org.openecomp.sdc.be.auditing.api.AuditEventFactory; @@ -27,10 +30,6 @@ 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.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Objects; public abstract class AuditBaseEventFactory implements AuditEventFactory { private AuditingActionEnum action; @@ -39,32 +38,24 @@ public abstract class AuditBaseEventFactory implements AuditEventFactory { this.action = Objects.requireNonNull(action); } - public AuditBaseEventFactory() {} - - public AuditingActionEnum getAction() { - return action; + public AuditBaseEventFactory() { } 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 { + } else { appendIfNotEmpty(lastName, builder); } appendIfNotEmpty(user.getEmail(), builder); appendIfNotEmpty(user.getRole(), builder); - return builder.toString(); } @@ -119,6 +110,10 @@ public abstract class AuditBaseEventFactory implements AuditEventFactory { return StringUtils.EMPTY; } + public AuditingActionEnum getAction() { + return action; + } + @Override //TODO implement in derived classes for ci testing public List> getQueryParams() { @@ -127,20 +122,14 @@ public abstract class AuditBaseEventFactory implements AuditEventFactory { @Override public final String getLogMessage() { - return String.format(getLogPattern(), getLogArgs()); + return String.format(getLogPattern(), getLogArgs()); } private Object[] getLogArgs() { - return Arrays.stream(getLogMessageParams()) - .map(AuditBaseEventFactory::buildValue) - .toArray(String[]::new); + return Arrays.stream(getLogMessageParams()).map(AuditBaseEventFactory::buildValue).toArray(String[]::new); } public abstract String getLogPattern(); public abstract String[] getLogMessageParams(); - - - - } 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 index 9176a1aa93..9233a1a73e 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl; import org.openecomp.sdc.be.model.ConsumerDefinition; @@ -36,18 +35,26 @@ public class AuditConsumerEventFactory extends AuditBaseEventFactory { this(action, commonFields, buildConsumerName(ecompUser), buildUserName(modifier)); } - public AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, - String ecompUser, String modifier, String timestamp) { + public AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String ecompUser, String modifier, String timestamp) { this(action, commonFields, ecompUser, modifier); this.event.setTimestamp1(timestamp); } - private AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, - String ecompUser, String modifier) { + private AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String ecompUser, String modifier) { super(action); event = new ConsumerEvent(getAction().getName(), commonFields, ecompUser, modifier); } + 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(); + } + @Override public String getLogPattern() { return LOG_STR; @@ -55,21 +62,11 @@ public class AuditConsumerEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getModifier(), event.getEcompUser(), event.getStatus(), event.getDesc()}; + return new String[]{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 index db394ccfd0..8bed7fe9c2 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -25,15 +24,16 @@ 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 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); + operationalEnvironmentType, operationalEnvironmentAction, tenantContext); } @Override @@ -43,11 +43,12 @@ public class AuditEcompOpEnvEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getOperationalEnvironmentAction(), - event.getOperationalEnvironmentId(), event.getOperationalEnvironmentName(), - event.getOperationalEnvironmentType(), event.getTenantContext()}; + return new String[]{event.getAction(), event.getOperationalEnvironmentAction(), event.getOperationalEnvironmentId(), + event.getOperationalEnvironmentName(), event.getOperationalEnvironmentType(), event.getTenantContext()}; } - @Override - public AuditingGenericEvent getDbEvent() { return event; } + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditGetUebClusterEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditGetUebClusterEventFactory.java index 9994f04a30..5239801658 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditGetUebClusterEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditGetUebClusterEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -31,7 +30,6 @@ public class AuditGetUebClusterEventFactory extends AuditBaseEventFactory { private final AuditingGetUebClusterEvent event; public AuditGetUebClusterEventFactory(CommonAuditData commonFields, String consumerId) { - super(AuditingActionEnum.GET_UEB_CLUSTER); event = new AuditingGetUebClusterEvent(getAction().getName(), commonFields, consumerId); } @@ -48,12 +46,11 @@ public class AuditGetUebClusterEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getConsumerId(), event.getTimestamp(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getConsumerId(), event.getTimestamp(), event.getStatus(), event.getDesc()}; } @Override public AuditingGenericEvent getDbEvent() { return event; } - } 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 0f94ad2ce7..71306666c4 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 @@ -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. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.auditing.impl; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -39,7 +38,6 @@ import org.springframework.stereotype.Component; public class AuditingManager { private static final Logger log = Logger.getLogger(AuditingManager.class.getName()); - private final AuditCassandraDao cassandraDao; private final ConfigurationProvider configurationProvider; @@ -54,7 +52,6 @@ public class AuditingManager { } String msg = factory.getLogMessage(); logAuditEvent(msg); - saveEventToCassandra(factory.getDbEvent()); return msg; } @@ -66,9 +63,8 @@ public class AuditingManager { } private void logAuditEvent(String msg, LoggerSdcAudit audit, String requestId) { - if(audit != null) { - audit.logEntry(LogLevel.INFO, Severity.OK, msg, - MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), requestId); + if (audit != null) { + audit.logEntry(LogLevel.INFO, Severity.OK, msg, MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), requestId); } } @@ -82,12 +78,10 @@ public class AuditingManager { private void logAuditEvent(final String formattedString) { log.trace("logAuditEvent - start"); log.debug(formattedString); - LogFieldsMdcHandler.getInstance() - .setAuditMessage(formattedString); - if (!LoggerSdcAudit.isFlowBeingTakenCare()){ + LogFieldsMdcHandler.getInstance().setAuditMessage(formattedString); + if (!LoggerSdcAudit.isFlowBeingTakenCare()) { log.debug("MOVED FROM AUDIT LOG: {}", formattedString); } log.trace("logAuditEvent - end"); } - } 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 index 919963be66..d4e1c37c58 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.category; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -29,20 +28,18 @@ import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; public class AuditCategoryEventFactory extends AuditBaseEventFactory { - private 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\""; + private 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\""; private final CategoryEvent event; - private AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String categoryName, String subCategoryName, String groupingName, String resourceType) { super(action); - event = new CategoryEvent(getAction().getName(), commonFields, modifier, categoryName, - subCategoryName, groupingName, resourceType); + event = new CategoryEvent(getAction().getName(), commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType); } - public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, - String categoryName, String subCategoryName, String groupingName, String resourceType) { + public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, String categoryName, + String subCategoryName, String groupingName, String resourceType) { this(action, commonFields, buildUserName(modifier), categoryName, subCategoryName, groupingName, resourceType); } @@ -59,14 +56,12 @@ public class AuditCategoryEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getModifier(), event.getCategoryName(), event.getSubCategoryName(), - event.getGroupingName(), event.getResourceType(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getModifier(), event.getCategoryName(), event.getSubCategoryName(), event.getGroupingName(), + event.getResourceType(), event.getStatus(), event.getDesc()}; } @Override public AuditingGenericEvent getDbEvent() { return event; } - - } 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 index 621d0b90a0..2038c1f377 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.category; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -30,7 +29,7 @@ import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; public class AuditGetCategoryHierarchyEventFactory extends AuditBaseEventFactory { private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\""; - private final GetCategoryHierarchyEvent event; + private final GetCategoryHierarchyEvent event; public AuditGetCategoryHierarchyEventFactory(CommonAuditData commonFields, User modifier, String details) { this(commonFields, buildUserName(modifier), details); @@ -53,13 +52,11 @@ public class AuditGetCategoryHierarchyEventFactory extends AuditBaseEventFactory @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()}; + return new String[]{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/distribution/AuditAddRemoveKeyDistributionEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistributionEngineEventFactory.java index f6dee4ca97..e7ea41b126 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistributionEngineEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistributionEngineEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -26,11 +25,10 @@ import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData; public class AuditAddRemoveKeyDistributionEngineEventFactory extends AuditDistributionEngineEventFactory { - private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" ROLE = \"%s\" " + - "API_KEY = \"%s\" STATUS = \"%s\""; + private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" ROLE = \"%s\" " + "API_KEY = \"%s\" STATUS = \"%s\""; - AuditAddRemoveKeyDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionTopicData distributionTopicData, - String apiKey, String envName, String role) { + AuditAddRemoveKeyDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, + DistributionTopicData distributionTopicData, String apiKey, String envName, String role) { super(action, commonFields, distributionTopicData, null, apiKey, envName, role); } @@ -42,8 +40,6 @@ public class AuditAddRemoveKeyDistributionEngineEventFactory extends AuditDistri @Override public String[] getLogMessageParams() { String topicName = event.getDnotifTopic() != null ? event.getDnotifTopic() : event.getDstatusTopic(); - return new String[] {event.getAction(), event.getEnvironmentName(), topicName, - event.getRole(), event.getApiKey(), event.getStatus()}; + return new String[]{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/AuditCreateTopicDistributionEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistributionEngineEventFactory.java index 038993475a..3cfc66935e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistributionEngineEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistributionEngineEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -28,9 +27,9 @@ public class AuditCreateTopicDistributionEngineEventFactory extends AuditDistrib private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" STATUS = \"%s\""; - AuditCreateTopicDistributionEngineEventFactory(CommonAuditData commonFields, DistributionTopicData distributionTopicData, - String apiKey, String envName, String role) { - super(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, commonFields, distributionTopicData,null, apiKey, envName, role); + AuditCreateTopicDistributionEngineEventFactory(CommonAuditData commonFields, DistributionTopicData distributionTopicData, String apiKey, + String envName, String role) { + super(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, commonFields, distributionTopicData, null, apiKey, envName, role); } @Override @@ -40,7 +39,6 @@ public class AuditCreateTopicDistributionEngineEventFactory extends AuditDistrib @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getEnvironmentName(), getTopicName(), event.getStatus()}; + return new String[]{event.getAction(), event.getEnvironmentName(), getTopicName(), event.getStatus()}; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDeployEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDeployEventFactory.java index b02c37cd85..eb04ab8bca 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDeployEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDeployEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -30,26 +29,25 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo; public class AuditDistributionDeployEventFactory extends AuditBaseEventFactory { - 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\""; + 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\""; private final DistributionDeployEvent event; - public AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, - String did, User modifier, String currentVersion) { + public AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, String did, User modifier, + String currentVersion) { this(commonFields, resourceCommonInfo, did, buildUserName(modifier), currentVersion); } - public AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, - String did, String modifier, String currentVersion, String timestamp) { + public AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, String did, String modifier, + String currentVersion, String timestamp) { this(commonFields, resourceCommonInfo, did, modifier, currentVersion); this.event.setTimestamp1(timestamp); } - private AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, - String did, String modifier, String currentVersion) { + private AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, String did, String modifier, + String currentVersion) { super(AuditingActionEnum.DISTRIBUTION_DEPLOY); - event = new DistributionDeployEvent(getAction().getName(), commonFields, resourceCommonInfo, did, modifier, - currentVersion); + event = new DistributionDeployEvent(getAction().getName(), commonFields, resourceCommonInfo, did, modifier, currentVersion); } @Override @@ -59,13 +57,12 @@ public class AuditDistributionDeployEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), - event.getCurrVersion(), event.getModifier(), event.getDid(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), event.getCurrVersion(), + event.getModifier(), event.getDid(), 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/AuditDistributionDownloadEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDownloadEventFactory.java index 0f1093e236..b18ac6aaac 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDownloadEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDownloadEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -38,8 +37,8 @@ public class AuditDistributionDownloadEventFactory extends AuditBaseEventFactory } public AuditDistributionDownloadEventFactory(CommonAuditData commonFields, DistributionData distributionData, String timestamp) { - this(commonFields, distributionData); - this.event.setTimestamp1(timestamp); + this(commonFields, distributionData); + this.event.setTimestamp1(timestamp); } @Override @@ -49,8 +48,7 @@ public class AuditDistributionDownloadEventFactory extends AuditBaseEventFactory @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getConsumerId(), event.getResourceUrl(), - event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getConsumerId(), event.getResourceUrl(), event.getStatus(), event.getDesc()}; } @Override diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactory.java index 38b240d50b..28b1de789c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -27,20 +26,18 @@ import org.openecomp.sdc.be.resources.data.auditing.DistributionEngineEvent; import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData; -public abstract class AuditDistributionEngineEventFactory extends AuditBaseEventFactory{ +public abstract class AuditDistributionEngineEventFactory extends AuditBaseEventFactory { protected final DistributionEngineEvent event; - AuditDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, - DistributionTopicData distributionTopicData, String consumerId, - String apiKey, String envName, String role) { + AuditDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionTopicData distributionTopicData, + String consumerId, String apiKey, String envName, String role) { super(action); event = new DistributionEngineEvent(getAction().getName(), commonFields, consumerId, distributionTopicData, apiKey, envName, role); } - AuditDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, - DistributionTopicData distributionTopicData, String consumerId, - String apiKey, String envName, String role, String timestamp) { + AuditDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionTopicData distributionTopicData, + String consumerId, String apiKey, String envName, String role, String timestamp) { this(action, commonFields, distributionTopicData, consumerId, apiKey, envName, role); this.event.setTimestamp1(timestamp); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactoryManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactoryManager.java index a964d13fb9..f4bb5bedf7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactoryManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactoryManager.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.auditing.api.AuditEventFactory; @@ -29,32 +28,24 @@ import org.openecomp.sdc.common.util.ThreadLocalsHolder; public class AuditDistributionEngineEventFactoryManager { public static AuditEventFactory createDistributionEngineEventFactory(AuditingActionEnum action, String environmentName, - DistributionTopicData distributionTopicData, String role, String apiKey, String status) { + DistributionTopicData distributionTopicData, String role, String apiKey, + String status) { AuditEventFactory factory; - switch (action) { case CREATE_DISTRIBUTION_TOPIC: factory = new AuditCreateTopicDistributionEngineEventFactory( - CommonAuditData.newBuilder() - .status(status) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - distributionTopicData, apiKey, environmentName, role); + CommonAuditData.newBuilder().status(status).requestId(ThreadLocalsHolder.getUuid()).build(), distributionTopicData, apiKey, + environmentName, role); break; case ADD_KEY_TO_TOPIC_ACL: case REMOVE_KEY_FROM_TOPIC_ACL: factory = new AuditAddRemoveKeyDistributionEngineEventFactory(action, - CommonAuditData.newBuilder() - .status(status) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - distributionTopicData, apiKey, environmentName, role); + CommonAuditData.newBuilder().status(status).requestId(ThreadLocalsHolder.getUuid()).build(), distributionTopicData, apiKey, + environmentName, role); break; default: throw new UnsupportedOperationException(); - } return factory; - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventMigrationFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventMigrationFactory.java index 1750d51c25..1c8a200ed6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventMigrationFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventMigrationFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -27,8 +26,8 @@ import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData; public class AuditDistributionEngineEventMigrationFactory extends AuditDistributionEngineEventFactory { public AuditDistributionEngineEventMigrationFactory(AuditingActionEnum action, CommonAuditData commonFields, - DistributionTopicData distributionTopicData, String consumerId, - String apiKey, String envName, String role, String timestamp) { + DistributionTopicData distributionTopicData, String consumerId, String apiKey, String envName, + String role, String timestamp) { super(action, commonFields, distributionTopicData, consumerId, apiKey, envName, role, timestamp); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionNotificationEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionNotificationEventFactory.java index 05a08cd80e..05664b926e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionNotificationEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionNotificationEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -32,35 +31,30 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; public class AuditDistributionNotificationEventFactory extends AuditBaseEventFactory { - 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\""; + 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\""; private final DistributionNotificationEvent event; public AuditDistributionNotificationEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo resourceVersionInfo, - String did, User modifier, String topicName, + ResourceVersionInfo resourceVersionInfo, String did, User modifier, String topicName, OperationalEnvAuditData opEnvFields) { - this(commonAuditData, resourceCommonInfo, - resourceVersionInfo, did, AuditBaseEventFactory.buildUserName(modifier), - topicName, opEnvFields); + this(commonAuditData, resourceCommonInfo, resourceVersionInfo, did, AuditBaseEventFactory.buildUserName(modifier), topicName, opEnvFields); } public AuditDistributionNotificationEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo resourceVersionInfo, - String did, String modifier, String topicName, + ResourceVersionInfo resourceVersionInfo, String did, String modifier, String topicName, OperationalEnvAuditData opEnvFields, String timestamp) { this(commonAuditData, resourceCommonInfo, resourceVersionInfo, did, modifier, topicName, opEnvFields); this.event.setTimestamp1(timestamp); } private AuditDistributionNotificationEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo resourceVersionInfo, - String did, String modifier, String topicName, - OperationalEnvAuditData opEnvFields) { + ResourceVersionInfo resourceVersionInfo, String did, String modifier, String topicName, + OperationalEnvAuditData opEnvFields) { super(AuditingActionEnum.DISTRIBUTION_NOTIFY); - this.event = new DistributionNotificationEvent(getAction().getName(), commonAuditData, resourceCommonInfo, - resourceVersionInfo, did, modifier, topicName, opEnvFields); + this.event = new DistributionNotificationEvent(getAction().getName(), commonAuditData, resourceCommonInfo, resourceVersionInfo, did, modifier, + topicName, opEnvFields); } @Override @@ -70,14 +64,13 @@ public class AuditDistributionNotificationEventFactory extends AuditBaseEventFac @Override public String[] getLogMessageParams() { - return new String[] {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()}; + return new String[]{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; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionStatusEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionStatusEventFactory.java index 6309bffa79..5cf312ff2a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionStatusEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionStatusEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -29,19 +28,18 @@ import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; public class AuditDistributionStatusEventFactory extends AuditBaseEventFactory { - 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\""; + 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\""; private final DistributionStatusEvent event; - public AuditDistributionStatusEventFactory(CommonAuditData commonFields, DistributionData distributionData, - String did, String topicName, String statusTime) { + public AuditDistributionStatusEventFactory(CommonAuditData commonFields, DistributionData distributionData, String did, String topicName, + String statusTime) { super(AuditingActionEnum.DISTRIBUTION_STATUS); - this.event = new DistributionStatusEvent(getAction().getName(), commonFields, distributionData, did, - topicName, statusTime); + this.event = new DistributionStatusEvent(getAction().getName(), commonFields, distributionData, did, topicName, statusTime); } - public AuditDistributionStatusEventFactory(CommonAuditData commonFields, DistributionData distributionData, - String did, String topicName, String statusTime, String timestamp) { + public AuditDistributionStatusEventFactory(CommonAuditData commonFields, DistributionData distributionData, String did, String topicName, + String statusTime, String timestamp) { this(commonFields, distributionData, did, topicName, statusTime); this.event.setTimestamp1(timestamp); } @@ -53,8 +51,8 @@ public class AuditDistributionStatusEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getDid(), event.getConsumerId(), event.getTopicName(), - event.getResoureURL(), event.getStatusTime(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getDid(), event.getConsumerId(), event.getTopicName(), event.getResoureURL(), + event.getStatusTime(), event.getStatus(), event.getDesc()}; } @Override diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistributionEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistributionEngineEventFactory.java index 88f1807bc5..a57bc987df 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistributionEngineEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistributionEngineEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.distribution; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -26,11 +25,11 @@ import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData; public class AuditRegUnregDistributionEngineEventFactory extends AuditDistributionEngineEventFactory { - 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\""; + 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 AuditRegUnregDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, - DistributionTopicData distrTopicData, String consumerId, String apiKey, String envName) { + public AuditRegUnregDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionTopicData distrTopicData, + String consumerId, String apiKey, String envName) { super(action, commonFields, distrTopicData, consumerId, apiKey, envName, null); } @@ -41,8 +40,7 @@ public class AuditRegUnregDistributionEngineEventFactory extends AuditDistributi @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getConsumerId(), event.getApiKey(), - event.getEnvironmentName(), event.getStatus(), event.getDesc(), - event.getDnotifTopic(), event.getDstatusTopic()}; + return new String[]{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/externalapi/AuditActivateServiceExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java index 1c77d0303e..2f80cac906 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.model.User; @@ -29,17 +28,13 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; public class AuditActivateServiceExternalApiEventFactory extends AuditExternalApiEventFactory { - private 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\""; + private 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, ResourceCommonInfo resourceCommonInfo, DistributionData distributionData, String invariantUuid, User modifier) { super(AuditingActionEnum.ACTIVATE_SERVICE_BY_API, commonFields, resourceCommonInfo, distributionData, - ResourceVersionInfo.newBuilder() - .build(), - ResourceVersionInfo.newBuilder() - .build(), - invariantUuid, modifier, null); + ResourceVersionInfo.newBuilder().build(), ResourceVersionInfo.newBuilder().build(), invariantUuid, modifier, null); } @Override @@ -49,8 +44,7 @@ public class AuditActivateServiceExternalApiEventFactory extends AuditExternalAp @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceType(), event.getConsumerId(), - event.getResourceURL(), event.getModifier(), event.getStatus(), - event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()}; + return new String[]{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 index 109c8395dc..74c0eb0c5c 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -28,17 +27,13 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; public class AuditAssetExternalApiEventFactory extends AuditExternalApiEventFactory { - private 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\""; + private 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, ResourceCommonInfo resourceCommonInfo, DistributionData distributionData) { - super(action, commonFields, resourceCommonInfo, distributionData, - ResourceVersionInfo.newBuilder() - .build(), - ResourceVersionInfo.newBuilder() - .build(), - null, null, null); + super(action, commonFields, resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), + ResourceVersionInfo.newBuilder().build(), null, null, null); } @Override @@ -48,7 +43,7 @@ public class AuditAssetExternalApiEventFactory extends AuditExternalApiEventFact @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getConsumerId(), event.getResourceURL(), event.getResourceName(), - event.getResourceType(), event.getServiceInstanceId(), event.getStatus(), event.getDesc()}; + return new String[]{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/AuditAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java index 3ab5efbb6e..cc5faf6d0c 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -30,14 +29,9 @@ public class AuditAssetListExternalApiEventFactory extends AuditExternalApiEvent private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\""; - public AuditAssetListExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, - DistributionData distributionData) { - super(action, commonFields, new ResourceCommonInfo(), distributionData, - ResourceVersionInfo.newBuilder() - .build(), - ResourceVersionInfo.newBuilder() - .build(), - null, null, null); + public AuditAssetListExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionData distributionData) { + super(action, commonFields, new ResourceCommonInfo(), distributionData, ResourceVersionInfo.newBuilder().build(), + ResourceVersionInfo.newBuilder().build(), null, null, null); } @Override @@ -47,7 +41,6 @@ public class AuditAssetListExternalApiEventFactory extends AuditExternalApiEvent @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getConsumerId(), event.getResourceURL(), - event.getStatus(), event.getDesc()}; + return new String[]{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 index 523560a07a..726550b128 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.model.User; @@ -29,15 +28,15 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; public class AuditChangeLifecycleExternalApiEventFactory 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\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + 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\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; public AuditChangeLifecycleExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, - DistributionData distributionData, ResourceVersionInfo prevParams, ResourceVersionInfo currParams, - String invariantUuid, User modifier) { - super(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API, commonFields, resourceCommonInfo, distributionData, prevParams, currParams, - invariantUuid, modifier, null); + DistributionData distributionData, ResourceVersionInfo prevParams, + ResourceVersionInfo currParams, String invariantUuid, User modifier) { + super(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API, commonFields, resourceCommonInfo, distributionData, prevParams, currParams, invariantUuid, + modifier, null); } @Override @@ -47,9 +46,8 @@ public class AuditChangeLifecycleExternalApiEventFactory extends AuditExternalAp @Override public String[] getLogMessageParams() { - return new String[] {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()}; + return new String[]{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 index 931bc08d93..011a0692dd 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.model.User; @@ -29,18 +28,15 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; 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\" CURR_VERSION = \"%s\" CURR_STATE = \"%s\" CURR_ARTIFACT_UUID = \"%s\" " + - "STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\""; + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" CURR_VERSION = \"%s\" CURR_STATE = \"%s\" CURR_ARTIFACT_UUID = \"%s\" " + + "STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\""; public AuditCreateResourceExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, DistributionData distributionData, ResourceVersionInfo currResourceVersionInfo, String invariantUuid, User modifier) { - super(AuditingActionEnum.CREATE_RESOURCE_BY_API, commonFields, resourceCommonInfo, distributionData, - ResourceVersionInfo.newBuilder() - .build(), - currResourceVersionInfo, - invariantUuid, modifier, null); + super(AuditingActionEnum.CREATE_RESOURCE_BY_API, commonFields, resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), + currResourceVersionInfo, invariantUuid, modifier, null); } @Override @@ -50,10 +46,8 @@ public class AuditCreateResourceExternalApiEventFactory extends AuditExternalApi @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), - event.getConsumerId(), event.getResourceURL(), event.getModifier(), - event.getCurrVersion(), event.getCurrState(), event.getCurrArtifactUuid(), - event.getStatus(), event.getServiceInstanceId(), event.getInvariantUuid(), - event.getDesc()}; + return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), event.getResourceURL(), + event.getModifier(), event.getCurrVersion(), event.getCurrState(), 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/AuditCreateServiceExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateServiceExternalApiEventFactory.java index 640b537f60..bd9603e3b8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateServiceExternalApiEventFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateServiceExternalApiEventFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.model.User; @@ -29,17 +28,13 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; public class AuditCreateServiceExternalApiEventFactory extends AuditExternalApiEventFactory { - private 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\""; + private 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 AuditCreateServiceExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, - DistributionData distributionData, String invariantUuid, User modifier) { - super(AuditingActionEnum.CREATE_SERVICE_BY_API, commonFields, resourceCommonInfo, distributionData, - ResourceVersionInfo.newBuilder() - .build(), - ResourceVersionInfo.newBuilder() - .build(), - invariantUuid, modifier, null); + DistributionData distributionData, String invariantUuid, User modifier) { + super(AuditingActionEnum.CREATE_SERVICE_BY_API, commonFields, resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), + ResourceVersionInfo.newBuilder().build(), invariantUuid, modifier, null); } @Override @@ -49,8 +44,7 @@ public class AuditCreateServiceExternalApiEventFactory extends AuditExternalApiE @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceType(), event.getConsumerId(), - event.getResourceURL(), event.getModifier(), event.getStatus(), - event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()}; + return new String[]{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/AuditCrudExternalApiArtifactEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java index 80dc24dc63..af13447094 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.model.User; @@ -29,15 +28,14 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; public 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\""; + 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, ResourceCommonInfo resourceCommonInfo, DistributionData distributionData, ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier, String artifactData) { - super(action, commonFields, resourceCommonInfo, distributionData, prevParams, currParams, - invariantUuid, modifier, artifactData); + super(action, commonFields, resourceCommonInfo, distributionData, prevParams, currParams, invariantUuid, modifier, artifactData); } @Override @@ -47,9 +45,8 @@ public class AuditCrudExternalApiArtifactEventFactory extends AuditExternalApiEv @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), - event.getConsumerId(), event.getResourceURL(), event.getModifier(), - event.getPrevArtifactUuid(), event.getCurrArtifactUuid(), event.getArtifactData(), - event.getStatus(), event.getDesc()}; + return new String[]{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/AuditDownloadArtifactExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java index 93d2d70af8..a915eaaf6d 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.model.User; @@ -34,10 +33,8 @@ public class AuditDownloadArtifactExternalApiEventFactory extends AuditExternalA public AuditDownloadArtifactExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, DistributionData distributionData, ResourceVersionInfo currResourceVersionInfo, User modifier) { - super(AuditingActionEnum.DOWNLOAD_ARTIFACT, commonFields, resourceCommonInfo, distributionData, - ResourceVersionInfo.newBuilder() - .build(), - currResourceVersionInfo, null, modifier, null); + super(AuditingActionEnum.DOWNLOAD_ARTIFACT, commonFields, resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), + currResourceVersionInfo, null, modifier, null); } @Override @@ -47,7 +44,6 @@ public class AuditDownloadArtifactExternalApiEventFactory extends AuditExternalA @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getConsumerId(), event.getResourceURL(), - event.getStatus(), event.getDesc()}; + return new String[]{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/AuditExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java index 2b9002fe59..3fa8c8fe47 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.externalapi; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -42,10 +41,12 @@ public abstract class AuditExternalApiEventFactory extends AuditBaseEventFactory if (commonAuditData.getRequestId() == null) { commonAuditData.setRequestId(ThreadLocalsHolder.getUuid()); } - event = new ExternalApiEvent(getAction().getName(), commonAuditData, resourceCommonInfo, distributionData, - prevParams, currParams, AuditBaseEventFactory.buildUserName(modifier), invariantUuid, artifactData) ; + event = new ExternalApiEvent(getAction().getName(), commonAuditData, resourceCommonInfo, distributionData, prevParams, currParams, + AuditBaseEventFactory.buildUserName(modifier), invariantUuid, artifactData); } @Override - public AuditingGenericEvent getDbEvent() { return event; } + public AuditingGenericEvent getDbEvent() { + return event; + } } 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 index 746fd2fe05..8f693a6147 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.model.User; @@ -29,16 +28,15 @@ 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\""; - + 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, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo prevParams, ResourceVersionInfo currParams, - String invariantUuid, User modifier, String artifactData, String comment, String did) { - super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, - modifier, artifactData, comment, did, Constants.EMPTY_STRING); + ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier, + String artifactData, String comment, String did) { + super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did, + Constants.EMPTY_STRING); } @Override @@ -48,10 +46,8 @@ public class AuditArtifactResourceAdminEventFactory extends AuditResourceAdminEv @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), - event.getServiceInstanceId(), event.getInvariantUUID(), event.getPrevVersion(), - event.getCurrVersion(), event.getModifier(), event.getPrevState(), - event.getCurrState(), event.getPrevArtifactUUID(), event.getCurrArtifactUUID(), - event.getArtifactData(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), + event.getInvariantUUID(), event.getPrevVersion(), event.getCurrVersion(), event.getModifier(), event.getPrevState(), event.getCurrState(), + event.getPrevArtifactUUID(), event.getCurrArtifactUUID(), event.getArtifactData(), event.getStatus(), 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 index d82f378100..9a48360c90 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.model.User; @@ -29,14 +28,15 @@ 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\""; + 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, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, ResourceVersionInfo currParams, - String invariantUuid, User modifier, String artifactData, String comment, String did) { - super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, - modifier, artifactData, comment, did, Constants.EMPTY_STRING); + public AuditCertificationResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, + ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did, + Constants.EMPTY_STRING); } @Override @@ -46,9 +46,8 @@ public class AuditCertificationResourceAdminEventFactory extends AuditResourceAd @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), - event.getServiceInstanceId(), event.getInvariantUUID(), event.getPrevVersion(), - event.getCurrVersion(), event.getModifier(), event.getPrevState(), - event.getCurrState(), event.getComment(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), + event.getInvariantUUID(), event.getPrevVersion(), event.getCurrVersion(), event.getModifier(), event.getPrevState(), event.getCurrState(), + event.getComment(), event.getStatus(), 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 index 237ce5283a..723d47aa5a 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.model.User; @@ -28,27 +27,27 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; 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\""; + 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 commonAuditData, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo prevParams, ResourceVersionInfo currParams, - String invariantUuid, User modifier, String artifactData, String comment, String did, String toscaNodeType) { - super(action, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, - modifier, artifactData, comment, did, toscaNodeType); + public AuditCreateUpdateResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonAuditData, + ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, + ResourceVersionInfo currParams, String invariantUuid, User modifier, String artifactData, + String comment, String did, String toscaNodeType) { + super(action, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did, + toscaNodeType); } @Override - public String getLogPattern() { - return LOG_STR; - } + public String getLogPattern() { + return LOG_STR; + } - @Override - public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), - event.getServiceInstanceId(), event.getInvariantUUID(), event.getPrevVersion(), - event.getCurrVersion(), event.getModifier(), event.getPrevState(), - event.getCurrState(), event.getStatus(), event.getDesc()}; + @Override + public String[] getLogMessageParams() { + return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), + event.getInvariantUUID(), event.getPrevVersion(), event.getCurrVersion(), event.getModifier(), event.getPrevState(), 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 index 2167744416..8fc09d9719 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.model.User; @@ -29,15 +28,15 @@ 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\""; + 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, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo prevParams, ResourceVersionInfo currParams, - String invariantUuid, User modifier, String artifactData, String comment, String did) { - super(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, - modifier, artifactData, comment, did, Constants.EMPTY_STRING); + ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, + artifactData, comment, did, Constants.EMPTY_STRING); } @Override @@ -47,9 +46,8 @@ public class AuditDistStateChangeRequestResourceAdminEventFactory extends AuditR @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), - event.getServiceInstanceId(), event.getCurrVersion(), event.getModifier(), - event.getCurrState(), event.getDprevStatus(), event.getDcurrStatus(), - event.getDid(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), event.getCurrVersion(), + event.getModifier(), event.getCurrState(), event.getDprevStatus(), event.getDcurrStatus(), event.getDid(), event.getStatus(), + 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 index c8a34b3b10..0b8d6e797e 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.model.User; @@ -29,16 +28,16 @@ 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\""; - + 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, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, - User modifier, String artifactData, String comment, String did) { - super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, - modifier, artifactData, comment, did, Constants.EMPTY_STRING); + public AuditDistStateChangeResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, + ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, + ResourceVersionInfo currParams, String invariantUuid, User modifier, String artifactData, + String comment, String did) { + super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did, + Constants.EMPTY_STRING); } @Override @@ -48,10 +47,8 @@ public class AuditDistStateChangeResourceAdminEventFactory extends AuditResource @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), - event.getServiceInstanceId(), event.getCurrVersion(), event.getModifier(), - event.getCurrState(), event.getDprevStatus(), event.getDcurrStatus(), - event.getStatus(), event.getDesc(), event.getComment()}; + return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), event.getCurrVersion(), + event.getModifier(), event.getCurrState(), event.getDprevStatus(), event.getDcurrStatus(), event.getStatus(), event.getDesc(), + 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 index 947e5adacd..af5a7aeec5 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.model.User; @@ -28,18 +27,20 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; public class AuditImportResourceAdminEventFactory extends AuditCreateUpdateResourceAdminEventFactory { - private static final String LOG_STR_TOSCA = LOG_STR + " TOSCA_NODE_TYPE = \"%s\"" ; + private static final String LOG_STR_TOSCA = LOG_STR + " TOSCA_NODE_TYPE = \"%s\""; - public AuditImportResourceAdminEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, ResourceVersionInfo currParams, - String invariantUuid, User modifier, String artifactData, String comment, String did, String toscaNodeType) { - super(AuditingActionEnum.IMPORT_RESOURCE, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, - modifier, artifactData, comment, did, toscaNodeType); + public AuditImportResourceAdminEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, + ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier, + String artifactData, String comment, String did, String toscaNodeType) { + super(AuditingActionEnum.IMPORT_RESOURCE, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, + comment, did, toscaNodeType); } - public AuditImportResourceAdminEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, ResourceVersionInfo currParams, - String invariantUuid, User modifier, String toscaNodeType) { - super(AuditingActionEnum.IMPORT_RESOURCE, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, - modifier, null, null, null, toscaNodeType); + public AuditImportResourceAdminEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, + ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier, + String toscaNodeType) { + super(AuditingActionEnum.IMPORT_RESOURCE, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, null, null, + null, toscaNodeType); } @Override @@ -49,9 +50,8 @@ public class AuditImportResourceAdminEventFactory extends AuditCreateUpdateResou @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), - event.getServiceInstanceId(), event.getInvariantUUID(), event.getPrevVersion(), - event.getCurrVersion(), event.getModifier(), event.getPrevState(), - event.getCurrState(), event.getStatus(), event.getDesc(), event.getToscaNodeType()}; + return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), + event.getInvariantUUID(), event.getPrevVersion(), event.getCurrVersion(), event.getModifier(), event.getPrevState(), event.getCurrState(), + event.getStatus(), event.getDesc(), 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 index 1de2031e83..9cccd3b732 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -33,34 +32,30 @@ public abstract class AuditResourceAdminEventFactory extends AuditBaseEventFacto protected final ResourceAdminEvent event; - AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, - ResourceVersionInfo currParams, String invariantUuid, - User modifier, String artifactData, String comment, String did, String toscaNodeType) { + AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, + ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier, + String artifactData, String comment, String did, String toscaNodeType) { this(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, AuditBaseEventFactory.buildUserName(modifier), - artifactData, AuditBaseEventFactory.replaceNullNameWithEmpty(comment), did, toscaNodeType); + artifactData, AuditBaseEventFactory.replaceNullNameWithEmpty(comment), did, toscaNodeType); } AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, - String modifier, String artifactData, String comment, String did, - String toscaNodeType, String timestamp) { - this(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, - artifactData, comment, did, toscaNodeType); + ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, String modifier, + String artifactData, String comment, String did, String toscaNodeType, String timestamp) { + this(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did, toscaNodeType); this.event.setTimestamp1(timestamp); } private AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, - String modifier, String artifactData, String comment, String did, - String toscaNodeType) { + ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, String modifier, + String artifactData, String comment, String did, String toscaNodeType) { super(action); this.event = new ResourceAdminEvent(getAction().getName(), commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, - artifactData, comment, did, toscaNodeType); + artifactData, comment, did, toscaNodeType); } @Override public AuditingGenericEvent getDbEvent() { return event; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventMigrationFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventMigrationFactory.java index 75ba231829..579971d909 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventMigrationFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventMigrationFactory.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -29,10 +28,10 @@ public class AuditResourceAdminEventMigrationFactory extends AuditResourceAdminE public AuditResourceAdminEventMigrationFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, - String modifier, String artifactData, String comment, String did, - String toscaNodeType, String timestamp) { - super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, - artifactData, comment, did, toscaNodeType, timestamp); + String modifier, String artifactData, String comment, String did, String toscaNodeType, + String timestamp) { + super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did, toscaNodeType, + timestamp); } @Override diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceEventFactoryManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceEventFactoryManager.java index 53b6f4bb9f..78cd70f228 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceEventFactoryManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceEventFactoryManager.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.resourceadmin; import org.openecomp.sdc.be.auditing.api.AuditEventFactory; @@ -30,16 +29,15 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; public class AuditResourceEventFactoryManager { - - public static AuditEventFactory createResourceEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, - ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, - User modifier, String artifactData, String comment, String did, String toscaNodeType) { + public static AuditEventFactory createResourceEventFactory(AuditingActionEnum action, CommonAuditData commonFields, + ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, + ResourceVersionInfo currParams, String invariantUuid, User modifier, + String artifactData, String comment, String did, String toscaNodeType) { AuditBaseEventFactory factory = null; - switch (action) { case IMPORT_RESOURCE: - factory = new AuditImportResourceAdminEventFactory(commonFields, resourceCommonInfo, prevParams, currParams, - invariantUuid, modifier, artifactData, comment, did, toscaNodeType); + factory = new AuditImportResourceAdminEventFactory(commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, + artifactData, comment, did, toscaNodeType); break; case CREATE_RESOURCE: case CREATE_SERVICE: @@ -48,7 +46,7 @@ public class AuditResourceEventFactoryManager { case RESTORE_COMPONENT: case UPDATE_SERVICE_METADATA: factory = new AuditCreateUpdateResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams, - invariantUuid, modifier, artifactData, comment, did, org.openecomp.sdc.common.api.Constants.EMPTY_STRING); + invariantUuid, modifier, artifactData, comment, did, org.openecomp.sdc.common.api.Constants.EMPTY_STRING); break; case CHECKIN_RESOURCE: case CHECKOUT_RESOURCE: @@ -61,29 +59,28 @@ public class AuditResourceEventFactoryManager { case UPDATE_SERVICE_REFERENCE: case VF_UPGRADE_SERVICES: factory = new AuditCertificationResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams, - invariantUuid, modifier, artifactData, comment, did); + 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, resourceCommonInfo, prevParams, currParams, - invariantUuid, modifier, artifactData, comment, did); + factory = new AuditArtifactResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, + modifier, artifactData, comment, did); break; case DISTRIBUTION_STATE_CHANGE_REQUEST: factory = new AuditDistStateChangeRequestResourceAdminEventFactory(commonFields, resourceCommonInfo, prevParams, currParams, - invariantUuid, modifier, artifactData, comment, did); + invariantUuid, modifier, artifactData, comment, did); break; case DISTRIBUTION_STATE_CHANGE_APPROV: case DISTRIBUTION_STATE_CHANGE_REJECT: factory = new AuditDistStateChangeResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams, - invariantUuid, modifier, artifactData, comment, did); + 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/usersadmin/AuditGetUsersListEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java index ae31873940..75d99a3da2 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.usersadmin; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -32,13 +31,11 @@ public class AuditGetUsersListEventFactory extends AuditBaseEventFactory { private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\""; private final GetUsersListEvent event; - public AuditGetUsersListEventFactory(CommonAuditData commonFields, User modifier, - String userDetails) { + public AuditGetUsersListEventFactory(CommonAuditData commonFields, User modifier, String userDetails) { this(commonFields, AuditBaseEventFactory.buildUserName(modifier), userDetails); } - public AuditGetUsersListEventFactory(CommonAuditData commonFields, String modifier, - String userDetails, String timestamp) { + public AuditGetUsersListEventFactory(CommonAuditData commonFields, String modifier, String userDetails, String timestamp) { this(commonFields, modifier, userDetails); this.event.setTimestamp1(timestamp); } @@ -55,12 +52,11 @@ public class AuditGetUsersListEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()}; + return new String[]{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 index 821c13f734..7063091a0e 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.usersadmin; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -53,12 +52,11 @@ public class AuditUserAccessEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getUserUid(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getUserUid(), 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/AuditUserAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java index 81236428c0..3d2b1331d4 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.auditing.impl.usersadmin; import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; @@ -33,20 +32,19 @@ public class AuditUserAdminEventFactory extends AuditBaseEventFactory { private final UserAdminEvent event; public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, User userBefore, User userAfter) { - this(action, commonFields, AuditBaseEventFactory.buildUserName(modifier), - AuditBaseEventFactory.buildUserNameExtended(userBefore), - AuditBaseEventFactory.buildUserNameExtended(userAfter)); + this(action, commonFields, AuditBaseEventFactory.buildUserName(modifier), AuditBaseEventFactory.buildUserNameExtended(userBefore), + AuditBaseEventFactory.buildUserNameExtended(userAfter)); } //Used by migration util - public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String userBefore, - String userAfter, String timestamp) { + public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String userBefore, String userAfter, + String timestamp) { this(action, commonFields, modifier, userBefore, userAfter); this.event.setTimestamp1(timestamp); } private AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String userBefore, - String userAfter) { + String userAfter) { super(action); event = new UserAdminEvent(action.getName(), commonFields, modifier, userBefore, userAfter); } @@ -58,14 +56,11 @@ public class AuditUserAdminEventFactory extends AuditBaseEventFactory { @Override public String[] getLogMessageParams() { - return new String[] {event.getAction(), event.getModifier(), event.getUserBefore(), - event.getUserAfter(), event.getStatus(), event.getDesc()}; + return new String[]{event.getAction(), event.getModifier(), event.getUserBefore(), event.getUserAfter(), event.getStatus(), event.getDesc()}; } @Override public AuditingGenericEvent getDbEvent() { return event; } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IComponentMessage.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IComponentMessage.java index 42a869137b..588bddbbd5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IComponentMessage.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IComponentMessage.java @@ -17,29 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.api; +import java.io.Serializable; import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; import org.openecomp.sdc.be.model.CatalogUpdateTimestamp; -import java.io.Serializable; - - - /** - * Represent Component (service, resource etc...) change message added to the - * message queue by sdc backend.
- * - * @author ms172g + * Represent Component (service, resource etc...) change message added to the message queue by sdc backend.
* + * @author ms172g */ public interface IComponentMessage extends Serializable, ITypeMessage { - /** - * Change Type - * @return - */ - ChangeTypeEnum getChangeType(); - CatalogUpdateTimestamp getCatalogUpdateTimestamp(); + /** + * Change Type + * + * @return + */ + ChangeTypeEnum getChangeType(); + + CatalogUpdateTimestamp getCatalogUpdateTimestamp(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IMessageQueueHandlerProducer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IMessageQueueHandlerProducer.java index 21c3ac8f2e..c898825a78 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IMessageQueueHandlerProducer.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IMessageQueueHandlerProducer.java @@ -17,12 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.api; public interface IMessageQueueHandlerProducer { - + IStatus pushMessage(ITypeMessage message); - IStatus init(); + IStatus init(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IStatus.java index dd21c2985d..7ffb6d01cc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IStatus.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IStatus.java @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.api; import org.openecomp.sdc.be.catalog.enums.ResultStatusEnum; @FunctionalInterface public interface IStatus { - + static IStatus getSuccessStatus() { - return () -> ResultStatusEnum.SUCCESS; } @@ -39,5 +37,4 @@ public interface IStatus { } ResultStatusEnum getResultStatus(); - -} \ No newline at end of file +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/ITypeMessage.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/ITypeMessage.java index a58e5f87c1..cec7313116 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/ITypeMessage.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/ITypeMessage.java @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.api; public interface ITypeMessage { + String getMessageType(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ChangeTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ChangeTypeEnum.java index 5107468af4..776c00bde4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ChangeTypeEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ChangeTypeEnum.java @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.enums; /** - * Represents The change type SDC Backend requests on the Component.
- * @author ms172g + * Represents The change type SDC Backend requests on the Component.
* + * @author ms172g */ -public enum ChangeTypeEnum { - LIFECYCLE, DELETE, ARCHIVE, RESTORE -} \ No newline at end of file +public enum ChangeTypeEnum { + LIFECYCLE, DELETE, ARCHIVE, RESTORE +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ResultStatusEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ResultStatusEnum.java index 53a242380c..925bd47b8d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ResultStatusEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ResultStatusEnum.java @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.enums; /** * Simple Status Enum - * @author ms172g * + * @author ms172g */ public enum ResultStatusEnum { - SUCCESS, FAIL , SERVICE_DISABLED -} \ No newline at end of file + SUCCESS, FAIL, SERVICE_DISABLED +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/ComponentMessage.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/ComponentMessage.java index 82b646714e..69a04e1df5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/ComponentMessage.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/ComponentMessage.java @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.impl; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import org.openecomp.sdc.be.catalog.api.IComponentMessage; import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -32,120 +32,116 @@ import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import java.util.List; - public class ComponentMessage extends CatalogComponent implements IComponentMessage { - /** - * - */ - private static final long serialVersionUID = 3233307722573636520L; - @JsonProperty("changeTypeEnum") - ChangeTypeEnum changeTypeEnum; - @JsonProperty("catalogUpdateTimestamp") - private CatalogUpdateTimestamp catalogUpdateTimestamp; - private Boolean isArchived; - - public ComponentMessage(Component component, ChangeTypeEnum changeTypeEnum, - CatalogUpdateTimestamp catalogUpdateTimestamp) { - super(); - - this.changeTypeEnum = changeTypeEnum; - this.catalogUpdateTimestamp = catalogUpdateTimestamp; - - setUniqueId(component.getUniqueId());// uniqueId - setUuid(component.getUUID()); // uuid - setInvariantUUID(component.getInvariantUUID()); // invariantUUID - - // View Fields - setName(component.getName()); // name - setSystemName(component.getSystemName()); // systemName - - setVersion(component.getVersion());// version - setLifecycleState(component.getLifecycleState() - .name()); // lifecycleState - setIcon(component.getIcon()); // icon - - ComponentTypeEnum componentType = component.getComponentType(); - setComponentType(componentType);// componentType - - buildCategories(component.getCategories()); // categoryNormalizedName, - // subCategoryNormalizedName - if (componentType == ComponentTypeEnum.SERVICE) { - Service service = (Service) component; - setDistributionStatus(service.getDistributionStatus() - .name()); // distributionStatus - } else { - Resource r = (Resource) component; - this.setResourceType(r.getResourceType() - .name()); // resourceType - } - setIsArchived(component.isArchived()); // isArchived - setIsHighestVersion(component.isHighestVersion()); // isHighestVersion - setDescription(component.getDescription()); // description - if (component.getTags() != null) { - setTags(component.getTags()); // tags - } - setLastUpdateDate(component.getLastUpdateDate());// lastUpdateDate - setLastUpdaterUserId(component.getLastUpdaterUserId()); - } - - private void buildCategories(List categories) { - if (categories != null) { - setCategories(categories); - CategoryDefinition categoryDefinition = categories.get(0); - - if (categoryDefinition != null) { - setCategoryNormalizedName(categoryDefinition.getName()); - List subcategories = categoryDefinition.getSubcategories(); - if (null != subcategories) { - SubCategoryDefinition subCategoryDefinition = subcategories.get(0); - - if (subCategoryDefinition != null) { - setSubCategoryNormalizedName(subCategoryDefinition.getName()); - } - } - } - } - } - - @Override - public ChangeTypeEnum getChangeType() { - return changeTypeEnum; - } - - @Override - public CatalogUpdateTimestamp getCatalogUpdateTimestamp() { - return catalogUpdateTimestamp; - } - - @Override - public String toString() { - return "ComponentMessage [ getChangeType()=" + getChangeType() + ", getCatalogUpdateTimestamp()=" - + getCatalogUpdateTimestamp() + ", getIsArchived()=" + getIsArchived() + ", getUuid()=" + getUuid() - + ", getInvariantUUID()=" + getInvariantUUID() + ", getSystemName()=" + getSystemName() - + ", getDescription()=" + getDescription() + ", getIsHighestVersion()=" + getIsHighestVersion() - + ", getCategoryNormalizedName()=" + getCategoryNormalizedName() + ", getSubCategoryNormalizedName()=" - + getSubCategoryNormalizedName() + ", getResourceType()=" + getResourceType() + ", getName()=" - + getName() + ", getLastUpdateDate()=" + getLastUpdateDate() + ", getVersion()=" + getVersion() - + ", getComponentType()=" + getComponentType() + ", getIcon()=" + getIcon() + ", getUniqueId()=" - + getUniqueId() + ", getLifecycleState()=" + getLifecycleState() + ", getDistributionStatus()=" - + getDistributionStatus() + ", getTags()=" + getTags() + ", getCategories()=" + getCategories() - + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() - + "]"; - } - - public Boolean getIsArchived() { - return isArchived; - } - - public void setIsArchived(Boolean isArchived) { - this.isArchived = isArchived; - } + /** + * + */ + private static final long serialVersionUID = 3233307722573636520L; + @JsonProperty("changeTypeEnum") + ChangeTypeEnum changeTypeEnum; + @JsonProperty("catalogUpdateTimestamp") + private CatalogUpdateTimestamp catalogUpdateTimestamp; + private Boolean isArchived; + + public ComponentMessage(Component component, ChangeTypeEnum changeTypeEnum, CatalogUpdateTimestamp catalogUpdateTimestamp) { + super(); + this.changeTypeEnum = changeTypeEnum; + this.catalogUpdateTimestamp = catalogUpdateTimestamp; + setUniqueId(component.getUniqueId());// uniqueId + + setUuid(component.getUUID()); // uuid + + setInvariantUUID(component.getInvariantUUID()); // invariantUUID + + // View Fields + + setName(component.getName()); // name + + setSystemName(component.getSystemName()); // systemName + + setVersion(component.getVersion());// version + setLifecycleState(component.getLifecycleState() + .name()); // lifecycleState + + setIcon(component.getIcon()); // icon + ComponentTypeEnum componentType = component.getComponentType(); + setComponentType(componentType);// componentType + + buildCategories(component.getCategories()); // categoryNormalizedName, + + // subCategoryNormalizedName + if (componentType == ComponentTypeEnum.SERVICE) { + Service service = (Service) component; + setDistributionStatus(service.getDistributionStatus() + .name()); // distributionStatus + } else { + Resource r = (Resource) component; + this.setResourceType(r.getResourceType() + .name()); // resourceType + } + setIsArchived(component.isArchived()); // isArchived + + setIsHighestVersion(component.isHighestVersion()); // isHighestVersion + + setDescription(component.getDescription()); // description + if (component.getTags() != null) { + setTags(component.getTags()); // tags + } + setLastUpdateDate(component.getLastUpdateDate());// lastUpdateDate + setLastUpdaterUserId(component.getLastUpdaterUserId()); + } + + private void buildCategories(List categories) { + if (categories != null) { + setCategories(categories); + CategoryDefinition categoryDefinition = categories.get(0); + if (categoryDefinition != null) { + setCategoryNormalizedName(categoryDefinition.getName()); + List subcategories = categoryDefinition.getSubcategories(); + if (null != subcategories) { + SubCategoryDefinition subCategoryDefinition = subcategories.get(0); + if (subCategoryDefinition != null) { + setSubCategoryNormalizedName(subCategoryDefinition.getName()); + } + } + } + } + } + + @Override + public ChangeTypeEnum getChangeType() { + return changeTypeEnum; + } + + @Override + public CatalogUpdateTimestamp getCatalogUpdateTimestamp() { + return catalogUpdateTimestamp; + } + + @Override + public String toString() { + return "ComponentMessage [ getChangeType()=" + getChangeType() + ", getCatalogUpdateTimestamp()=" + getCatalogUpdateTimestamp() + + ", getIsArchived()=" + getIsArchived() + ", getUuid()=" + getUuid() + ", getInvariantUUID()=" + getInvariantUUID() + + ", getSystemName()=" + getSystemName() + ", getDescription()=" + getDescription() + ", getIsHighestVersion()=" + getIsHighestVersion() + + ", getCategoryNormalizedName()=" + getCategoryNormalizedName() + ", getSubCategoryNormalizedName()=" + getSubCategoryNormalizedName() + + ", getResourceType()=" + getResourceType() + ", getName()=" + getName() + ", getLastUpdateDate()=" + getLastUpdateDate() + + ", getVersion()=" + getVersion() + ", getComponentType()=" + getComponentType() + ", getIcon()=" + getIcon() + ", getUniqueId()=" + + getUniqueId() + ", getLifecycleState()=" + getLifecycleState() + ", getDistributionStatus()=" + getDistributionStatus() + ", getTags()=" + + getTags() + ", getCategories()=" + getCategories() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + + super.toString() + "]"; + } + + public Boolean getIsArchived() { + return isArchived; + } + + public void setIsArchived(Boolean isArchived) { + this.isArchived = isArchived; + } @Override public String getMessageType() { return getClass().getSimpleName(); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java index a442481258..855ef64d9c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.impl; import com.att.nsa.mr.client.MRBatchingPublisher; @@ -45,8 +44,7 @@ public class DmaapProducer implements IMessageQueueHandlerProducer { private final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); private MRBatchingPublisher publisher; - public DmaapProducer(final DmaapClientFactory dmaapClientFactory, - final DmaapProducerHealth dmaapHealth) { + public DmaapProducer(final DmaapClientFactory dmaapClientFactory, final DmaapProducerHealth dmaapHealth) { this.dmaapClientFactory = dmaapClientFactory; this.dmaapHealth = dmaapHealth; } @@ -54,18 +52,15 @@ public class DmaapProducer implements IMessageQueueHandlerProducer { @Override public IStatus pushMessage(ITypeMessage message) { try { - DmaapProducerConfiguration producerConfiguration = configurationManager.getConfiguration() - .getDmaapProducerConfiguration(); + DmaapProducerConfiguration producerConfiguration = configurationManager.getConfiguration().getDmaapProducerConfiguration(); if (!producerConfiguration.getActive()) { - LOG.info( - "[Microservice DMAAP] producer is disabled [re-enable in configuration->isActive],message not sent."); + LOG.info("[Microservice DMAAP] producer is disabled [re-enable in configuration->isActive],message not sent."); dmaapHealth.report(false); return IStatus.getServiceDisabled(); } if (publisher == null) { IStatus initStatus = init(); if (initStatus.getResultStatus() != ResultStatusEnum.SUCCESS) { - return initStatus; } } @@ -73,23 +68,17 @@ public class DmaapProducer implements IMessageQueueHandlerProducer { String jsonInString = mapper.writeValueAsString(message); if (publisher != null) { LOG.info("before send message . response {}", jsonInString); - - LOG.invoke("Dmaap Producer", "DmaapProducer-pushMessage", DmaapProducer.class.getName(), - message.toString()); - + LOG.invoke("Dmaap Producer", "DmaapProducer-pushMessage", DmaapProducer.class.getName(), message.toString()); int pendingMsg = publisher.send(jsonInString); LOG.info("sent message . response {}", pendingMsg); - LOG.invokeReturn(producerConfiguration.getConsumerId(), "Dmaap Producer", - StatusCode.COMPLETE.getStatusCode(), "DmaapProducer-pushMessage", message.toString(), pendingMsg); - + LOG.invokeReturn(producerConfiguration.getConsumerId(), "Dmaap Producer", StatusCode.COMPLETE.getStatusCode(), + "DmaapProducer-pushMessage", message.toString(), pendingMsg); } - dmaapHealth.report(true); } catch (Exception e) { LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, "Failed to send message . Exception {}", e.getMessage()); return IStatus.getFailStatus(); } - return IStatus.getSuccessStatus(); } @@ -97,8 +86,7 @@ public class DmaapProducer implements IMessageQueueHandlerProducer { @Override public IStatus init() { LOG.debug("MessageQueueHandlerProducer:: Start initializing"); - DmaapProducerConfiguration configuration = configurationManager.getConfiguration() - .getDmaapProducerConfiguration(); + DmaapProducerConfiguration configuration = configurationManager.getConfiguration().getDmaapProducerConfiguration(); if (configuration.getActive()) { try { publisher = dmaapClientFactory.createProducer(configuration); @@ -107,7 +95,6 @@ public class DmaapProducer implements IMessageQueueHandlerProducer { dmaapHealth.report(false); return IStatus.getFailStatus(); } - } catch (Exception e) { LOG.error("Failed to connect to topic . Exeption {}", e.getMessage()); dmaapHealth.report(false); @@ -130,9 +117,6 @@ public class DmaapProducer implements IMessageQueueHandlerProducer { } } catch (Exception e) { LOG.error("Failed to close messageQ . Exeption {}", e.getMessage()); - } - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerHealth.java index b62df86b4b..4000be39b3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerHealth.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerHealth.java @@ -17,9 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.catalog.impl; +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 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.DmaapProducerConfiguration; @@ -28,75 +34,37 @@ import org.openecomp.sdc.common.api.HealthCheckInfo; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -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; - @Component("dmaapProducerHealth") public class DmaapProducerHealth { - private static final String DMAAP_HEALTH_LOG_CONTEXT = "dmaapProducer.healthcheck"; private static final String DMAAP_HEALTH_CHECK_STR = "dmaapProducerHealthCheck"; private static final Logger log = Logger.getLogger(DmaapProducerHealth.class.getName()); private static final Logger logHealth = Logger.getLogger(DMAAP_HEALTH_LOG_CONTEXT); + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private HealthCheckInfo healthCheckInfo = DmaapProducerHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); private long healthCheckReadTimeout = 20; private long reconnectInterval = 5; - private HealthCheckScheduledTask healthCheckScheduledTask = null ; - private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + private HealthCheckScheduledTask healthCheckScheduledTask = null; private ScheduledFuture scheduledFuture = null; - private DmaapProducerConfiguration configuration = null ; - + private DmaapProducerConfiguration configuration = null; private volatile AtomicBoolean lastHealthState = new AtomicBoolean(false); private volatile AtomicBoolean reportedHealthState = null; - public enum HealthCheckInfoResult { - OK(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())), - UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())), - DOWN(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, 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("DmaapProducer is not available"),DOWN("DOWN"), NOT_CONFIGURED("DmaapProducer configuration is missing/wrong "); - - private String desc; - DmaapStatusDescription(String desc) { - this.desc = desc; - } - public String getDescription() { - return desc; - } - - } - @PostConstruct public DmaapProducerHealth init() { log.trace("Enter init method of DmaapProducer health"); - synchronized (DmaapProducerHealth.class){ + synchronized (DmaapProducerHealth.class) { this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapProducerConfiguration(); - Integer pollingInterval = configuration.getPollingInterval(); - if (pollingInterval != null && pollingInterval!=0) { + 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 + this.healthCheckScheduledTask = new HealthCheckScheduledTask(configuration); //what is the representation? csv? delimiter? json or other startHealthCheckTask(true); } log.trace("Exit init method of DistributionEngineClusterHealth"); @@ -120,75 +88,108 @@ public class DmaapProducerHealth { * @param startTask */ private void startHealthCheckTask(boolean startTask) { - synchronized (DmaapProducerHealth.class){ + synchronized (DmaapProducerHealth.class) { if (startTask && this.scheduledFuture == null) { - this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS); + this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); } } } - void report(Boolean isUp){ - if (reportedHealthState == null) + void report(Boolean isUp) { + if (reportedHealthState == null) { reportedHealthState = new AtomicBoolean(isUp); + } reportedHealthState.set(isUp); } - public HealthCheckInfo getHealthCheckInfo() { return healthCheckInfo; } + public enum HealthCheckInfoResult { + // @formatter:off + OK(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())), + UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())), + DOWN(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription())); + // @formatter:on + + private HealthCheckInfo healthCheckInfo; + + HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { + this.healthCheckInfo = healthCheckInfo; + } + + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + } + + public enum DmaapStatusDescription { + // @formatter:off + OK("OK"), + UNAVAILABLE("DmaapProducer is not available"), + DOWN("DOWN"), + NOT_CONFIGURED("DmaapProducer configuration is missing/wrong "); + // @formatter:on + + private String desc; + + DmaapStatusDescription(String desc) { + this.desc = desc; + } + + public String getDescription() { + return desc; + } + + } + /** * Health Check Task Scheduler - infinite check. */ public class HealthCheckScheduledTask implements Runnable { - private final DmaapProducerConfiguration config; + private static final int TIMEOUT = 8192; + private final DmaapProducerConfiguration config; - HealthCheckScheduledTask(final DmaapProducerConfiguration config){ + HealthCheckScheduledTask(final DmaapProducerConfiguration config) { this.config = config; } + @Override public void run() { logHealth.trace("Executing Dmaap Health Check Task - Start"); boolean prevIsReachable; boolean reachable; //first try simple ping - try{ - if ( reportedHealthState != null ){ + try { + if (reportedHealthState != null) { reachable = reportedHealthState.get(); + } else { + reachable = false; } - else{ - reachable = false; - } - prevIsReachable = lastHealthState.getAndSet( reachable ); + 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 ); + } 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() ); + if (prevIsReachable != lastHealthState.get()) { + logAlarm(lastHealthState.get()); + } } - - - private void logAlarm(boolean lastHealthState) { - try{ - if ( lastHealthState ) { - BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery( DMAAP_HEALTH_CHECK_STR ); + try { + if (lastHealthState) { + BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery(DMAAP_HEALTH_CHECK_STR); } else { - BeEcompErrorManager.getInstance().logDmaapHealthCheckError( DMAAP_HEALTH_CHECK_STR ); + BeEcompErrorManager.getInstance().logDmaapHealthCheckError(DMAAP_HEALTH_CHECK_STR); } - }catch( Exception e ){ - log.debug("cannot logAlarm -> {}" ,e ); + } catch (Exception e) { + log.debug("cannot logAlarm -> {}", e); } } - } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java index 0762872797..e54864992a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -29,19 +28,20 @@ public interface ArtifactsResolver { /** * searching for an artifact with the give {@code artifactId} on the given {@code component} - * @param component the component to look for artifact in + * + * @param component the component to look for artifact in * @param componentType the type of the component to look for artifact in - * @param artifactId the id of the artifact to find + * @param artifactId the id of the artifact to find * @return the found artifact or null if not exist */ ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId); /** * searching for an artifact with the give {@code artifactId} on the given {@code componentInstance} + * * @param componentInstance the component instance to look for the artifact in - * @param artifactId the if of the artifact to find + * @param artifactId the if of the artifact to find * @return the found artifact or null if not exist */ ArtifactDefinition findArtifactOnComponentInstance(ComponentInstance componentInstance, String artifactId); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarationOrchestrator.java index e023be4dec..7ad04ab3e1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarationOrchestrator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarationOrchestrator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.attribute; import static org.apache.commons.collections.MapUtils.isNotEmpty; @@ -55,8 +54,7 @@ public class AttributeDeclarationOrchestrator { return attributeDeclarator.declareAttributesAsOutputs(component, attributesToDeclare.getLeft(), attributesToDeclare.getRight()); } - public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, - final OutputDefinition outputToDelete) { + public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition outputToDelete) { log.debug("#unDeclareAttributesAsOutputs - removing output declaration for output {} on component {}", outputToDelete.getName(), component.getUniqueId()); for (final AttributeDeclarator attributeDeclarator : attributeDeclaratorsToOutput) { @@ -68,7 +66,6 @@ public class AttributeDeclarationOrchestrator { } } return StorageOperationStatus.OK; - } private AttributeDeclarator getAttributeDeclarator(final ComponentInstOutputsMap componentInstOutputsMap) { @@ -79,7 +76,5 @@ public class AttributeDeclarationOrchestrator { return componentInstanceAttributeDeclarator; } throw new IllegalStateException("there are no properties selected for declaration"); - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarator.java index 3fa68fa00c..80d1e5bfb9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.attribute; import fj.data.Either; @@ -33,21 +32,19 @@ public interface AttributeDeclarator { * creates a list of outputs from the given list of attributes and updates the attributes accordingly * * @param component the container - * @param propertiesOwnerId the id of the owner of the attributes to declare (e.g ComponentInstance, Policy, Group - * etc) - * @param attribsToDeclare the list of attributes that are being declared as outputs + * @param propertiesOwnerId the id of the owner of the attributes to declare (e.g ComponentInstance, Policy, Group etc) + * @param attribsToDeclare the list of attributes that are being declared as outputs * @return the list of outputs that were created from the given attributes */ - Either, StorageOperationStatus> declareAttributesAsOutputs(final Component component, - final String propertiesOwnerId, + Either, StorageOperationStatus> declareAttributesAsOutputs(final Component component, final String propertiesOwnerId, final List attribsToDeclare); /** - * returns the values of declared attributes 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. + * returns the values of declared attributes 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 output the input to be deleted + * @param output the input to be deleted */ StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition output); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentAttributeDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentAttributeDeclarator.java index 56dec5d93a..9b3487dbc9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentAttributeDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentAttributeDeclarator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.attribute; import fj.data.Either; @@ -39,102 +38,83 @@ import org.openecomp.sdc.be.model.operations.impl.AttributeOperation; @org.springframework.stereotype.Component public class ComponentAttributeDeclarator extends DefaultAttributeDeclarator { - private final ToscaOperationFacade toscaOperationFacade; - private final AttributeBusinessLogic attributeBusinessLogic; + private final ToscaOperationFacade toscaOperationFacade; + private final AttributeBusinessLogic attributeBusinessLogic; - public ComponentAttributeDeclarator(final ComponentsUtils componentsUtils, - final AttributeOperation attributeOperation, - final ToscaOperationFacade toscaOperationFacade, - final AttributeBusinessLogic attributeBusinessLogic) { + public ComponentAttributeDeclarator(final ComponentsUtils componentsUtils, final AttributeOperation attributeOperation, + final ToscaOperationFacade toscaOperationFacade, final AttributeBusinessLogic attributeBusinessLogic) { // super(componentsUtils, attributeOperation); - this.toscaOperationFacade = toscaOperationFacade; - this.attributeBusinessLogic = attributeBusinessLogic; - } - - @Override - public AttributeDataDefinition createDeclaredAttribute(final AttributeDataDefinition attributeDataDefinition) { - return new AttributeDataDefinition(attributeDataDefinition); - } - - @Override - public Either updateAttributesValues(final Component component, - final String propertiesOwnerId, - final List attributetypeList) { - if (CollectionUtils.isNotEmpty(attributetypeList)) { - for (AttributeDataDefinition attribute : attributetypeList) { - Either - storageStatus = toscaOperationFacade - .updateAttributeOfComponent(component, new AttributeDefinition(attribute)); - if (storageStatus.isRight()) { - return Either.right(storageStatus.right().value()); - } - } + this.toscaOperationFacade = toscaOperationFacade; + this.attributeBusinessLogic = attributeBusinessLogic; } - return Either.left(attributetypeList); - } - - @Override - public Optional resolvePropertiesOwner(final Component component, final String propertiesOwnerId) { - return Optional.of(component); - } - @Override - public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, - final OutputDefinition output) { - AttributeDefinition attributeDefinition = new AttributeDefinition(output); - - // TODO - do we need this one - if (attributeBusinessLogic.isAttributeUsedByOperation(component, attributeDefinition)) { - return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION; + @Override + public AttributeDataDefinition createDeclaredAttribute(final AttributeDataDefinition attributeDataDefinition) { + return new AttributeDataDefinition(attributeDataDefinition); } - Optional attributeToUpdateCandidate = - getDeclaredAttributeByOutputId(component, output.getUniqueId()); - - if (attributeToUpdateCandidate.isPresent()) { - AttributeDefinition attributeToUpdate = attributeToUpdateCandidate.get(); - return unDeclareOutput(component, output, attributeToUpdate); + @Override + public Either updateAttributesValues(final Component component, final String propertiesOwnerId, + final List attributetypeList) { + if (CollectionUtils.isNotEmpty(attributetypeList)) { + for (AttributeDataDefinition attribute : attributetypeList) { + Either storageStatus = toscaOperationFacade + .updateAttributeOfComponent(component, new AttributeDefinition(attribute)); + if (storageStatus.isRight()) { + return Either.right(storageStatus.right().value()); + } + } + } + return Either.left(attributetypeList); } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus unDeclareOutput(final Component component, - final OutputDefinition output, - final AttributeDefinition attributeToUpdate) { - prepareValueBeforeDelete(output, attributeToUpdate, Collections.emptyList()); - attributeToUpdate.setValue(output.getDefaultValue()); - Either status = toscaOperationFacade - .updateAttributeOfComponent(component, attributeToUpdate); - if (status.isRight()) { - return status.right().value(); + @Override + public Optional resolvePropertiesOwner(final Component component, final String propertiesOwnerId) { + return Optional.of(component); } - return StorageOperationStatus.OK; - } - - private Optional getDeclaredAttributeByOutputId(final Component component, final String outputId) { - List attributes = component.getAttributes(); - - if (CollectionUtils.isEmpty(attributes)) { - return Optional.empty(); + @Override + public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition output) { + AttributeDefinition attributeDefinition = new AttributeDefinition(output); + // TODO - do we need this one + if (attributeBusinessLogic.isAttributeUsedByOperation(component, attributeDefinition)) { + return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION; + } + Optional attributeToUpdateCandidate = getDeclaredAttributeByOutputId(component, output.getUniqueId()); + if (attributeToUpdateCandidate.isPresent()) { + AttributeDefinition attributeToUpdate = attributeToUpdateCandidate.get(); + return unDeclareOutput(component, output, attributeToUpdate); + } + return StorageOperationStatus.OK; } - for (AttributeDefinition attributeDefinition : attributes) { - List getOutputValues = attributeDefinition.getGetOutputValues(); - if (CollectionUtils.isEmpty(getOutputValues)) { - continue; - } - - Optional getOutputCandidate = - getOutputValues.stream().filter(getOutput -> getOutput.getOutputId().equals(outputId)).findAny(); - - if (getOutputCandidate.isPresent()) { - return Optional.of(attributeDefinition); - } + private StorageOperationStatus unDeclareOutput(final Component component, final OutputDefinition output, + final AttributeDefinition attributeToUpdate) { + prepareValueBeforeDelete(output, attributeToUpdate, Collections.emptyList()); + attributeToUpdate.setValue(output.getDefaultValue()); + Either status = toscaOperationFacade.updateAttributeOfComponent(component, attributeToUpdate); + if (status.isRight()) { + return status.right().value(); + } + return StorageOperationStatus.OK; } - return Optional.empty(); - } - + private Optional getDeclaredAttributeByOutputId(final Component component, final String outputId) { + List attributes = component.getAttributes(); + if (CollectionUtils.isEmpty(attributes)) { + return Optional.empty(); + } + for (AttributeDefinition attributeDefinition : attributes) { + List getOutputValues = attributeDefinition.getGetOutputValues(); + if (CollectionUtils.isEmpty(getOutputValues)) { + continue; + } + Optional getOutputCandidate = getOutputValues.stream() + .filter(getOutput -> getOutput.getOutputId().equals(outputId)).findAny(); + if (getOutputCandidate.isPresent()) { + return Optional.of(attributeDefinition); + } + } + return Optional.empty(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceAttributeDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceAttributeDeclarator.java index 8981515ea4..0882edaa4f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceAttributeDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceAttributeDeclarator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.attribute; import fj.data.Either; @@ -39,15 +38,13 @@ import org.openecomp.sdc.be.model.operations.impl.AttributeOperation; import org.openecomp.sdc.common.log.wrappers.Logger; @org.springframework.stereotype.Component -public class ComponentInstanceAttributeDeclarator extends - DefaultAttributeDeclarator { +public class ComponentInstanceAttributeDeclarator extends DefaultAttributeDeclarator { private static final Logger log = Logger.getLogger(ComponentInstanceAttributeDeclarator.class); private ToscaOperationFacade toscaOperationFacade; private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - public ComponentInstanceAttributeDeclarator(final ComponentsUtils componentsUtils, - final AttributeOperation attributeOperation, + public ComponentInstanceAttributeDeclarator(final ComponentsUtils componentsUtils, final AttributeOperation attributeOperation, final ToscaOperationFacade toscaOperationFacade, final ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { // super(componentsUtils, attributeOperation); @@ -61,8 +58,7 @@ public class ComponentInstanceAttributeDeclarator extends } @Override - public Either updateAttributesValues(final Component component, - final String cmptInstanceId, + public Either updateAttributesValues(final Component component, final String cmptInstanceId, final List attributetypeList) { log.debug("#updateAttributesValues - updating component instance attributes for instance {} on component {}", cmptInstanceId, component.getUniqueId()); @@ -78,17 +74,15 @@ public class ComponentInstanceAttributeDeclarator extends @Override public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition output) { - - final List componentInstancePropertiesDeclaredAsInput - = componentInstanceBusinessLogic.getComponentInstanceAttributesByOutputId(component, output.getUniqueId()); + final List componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic + .getComponentInstanceAttributesByOutputId(component, output.getUniqueId()); if (CollectionUtils.isEmpty(componentInstancePropertiesDeclaredAsInput)) { return StorageOperationStatus.OK; } - componentInstancePropertiesDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDelete(output, - cmptInstanceProperty, cmptInstanceProperty.getPath())); - return toscaOperationFacade.updateComponentInstanceAttributes(component, - componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(), - componentInstancePropertiesDeclaredAsInput); + componentInstancePropertiesDeclaredAsInput + .forEach(cmptInstanceProperty -> prepareValueBeforeDelete(output, cmptInstanceProperty, cmptInstanceProperty.getPath())); + return toscaOperationFacade + .updateComponentInstanceAttributes(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(), + componentInstancePropertiesDeclaredAsInput); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceOutputAttributeDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceOutputAttributeDeclarator.java index 7ded7c1209..989cc97069 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceOutputAttributeDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceOutputAttributeDeclarator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.attribute; import static org.apache.commons.collections4.CollectionUtils.isEmpty; @@ -46,8 +45,7 @@ public class ComponentInstanceOutputAttributeDeclarator extends DefaultAttribute private final ToscaOperationFacade toscaOperationFacade; private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - public ComponentInstanceOutputAttributeDeclarator(final ComponentsUtils componentsUtils, - final AttributeOperation attributeOperation, + public ComponentInstanceOutputAttributeDeclarator(final ComponentsUtils componentsUtils, final AttributeOperation attributeOperation, final ToscaOperationFacade toscaOperationFacade, final ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { // super(componentsUtils, attributeOperation); @@ -61,8 +59,7 @@ public class ComponentInstanceOutputAttributeDeclarator extends DefaultAttribute } @Override - public Either updateAttributesValues(final Component component, - final String cmptInstanceId, + public Either updateAttributesValues(final Component component, final String cmptInstanceId, final List attributetypeList) { log.debug("#updateAttributesValues - updating component instance outputs for instance {} on component {}", cmptInstanceId, component.getUniqueId()); @@ -78,8 +75,7 @@ public class ComponentInstanceOutputAttributeDeclarator extends DefaultAttribute public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition output) { List componentInstanceInputsByInputId = componentInstanceBusinessLogic - .getComponentInstanceOutputsByOutputId(component, output - .getUniqueId()); + .getComponentInstanceOutputsByOutputId(component, output.getUniqueId()); if (isEmpty(componentInstanceInputsByInputId)) { return StorageOperationStatus.OK; } @@ -88,5 +84,4 @@ public class ComponentInstanceOutputAttributeDeclarator extends DefaultAttribute return toscaOperationFacade.updateComponentInstanceOutputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), componentInstanceInputsByInputId); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/DefaultAttributeDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/DefaultAttributeDeclarator.java index e53a362508..915959b7cd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/DefaultAttributeDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/DefaultAttributeDeclarator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.attribute; import static org.openecomp.sdc.common.api.Constants.GET_ATTRIBUTE; @@ -53,8 +52,8 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.yaml.snakeyaml.Yaml; -public abstract class DefaultAttributeDeclarator - implements AttributeDeclarator { +public abstract class DefaultAttributeDeclarator implements + AttributeDeclarator { private static final Logger log = Logger.getLogger(DefaultAttributeDeclarator.class); private static final short LOOP_PROTECTION_LEVEL = 10; @@ -68,9 +67,8 @@ public abstract class DefaultAttributeDeclarator, StorageOperationStatus> declareAttributesAsOutputs(final Component component, final String propertiesOwnerId, final List attribsToDeclare) { - log.debug( - "#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", - component.getUniqueId(), propertiesOwnerId); + log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), + propertiesOwnerId); return resolvePropertiesOwner(component, propertiesOwnerId) .map(propertyOwner -> declareAttributesAsOutputs(component, propertyOwner, attribsToDeclare)) .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId))); @@ -78,31 +76,26 @@ public abstract class DefaultAttributeDeclarator updateAttributesValues(final Component component, - final String propertiesOwnerId, + protected abstract Either updateAttributesValues(final Component component, final String propertiesOwnerId, final List attributetypeList); protected abstract Optional resolvePropertiesOwner(final Component component, final String propertiesOwnerId); private StorageOperationStatus onPropertiesOwnerNotFound(final String componentId, final String propertiesOwnerId) { - log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, - componentId); + log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, componentId); return StorageOperationStatus.NOT_FOUND; } private Either, StorageOperationStatus> declareAttributesAsOutputs(final Component component, final PROPERTYOWNER propertiesOwner, final List attributesToDeclare) { - final AttributesDeclarationData attributesDeclarationData - = createOutputsAndOverrideAttributesValues(component, propertiesOwner, attributesToDeclare); - return updateAttributesValues(component, propertiesOwner.getUniqueId(), - attributesDeclarationData.getAttributesToUpdate()) - .left() + final AttributesDeclarationData attributesDeclarationData = createOutputsAndOverrideAttributesValues(component, propertiesOwner, + attributesToDeclare); + return updateAttributesValues(component, propertiesOwner.getUniqueId(), attributesDeclarationData.getAttributesToUpdate()).left() .map(updatePropsRes -> attributesDeclarationData.getOutputsToCreate()); } - private AttributesDeclarationData createOutputsAndOverrideAttributesValues(final Component component, - final PROPERTYOWNER propertiesOwner, + private AttributesDeclarationData createOutputsAndOverrideAttributesValues(final Component component, final PROPERTYOWNER propertiesOwner, final List attributesToDeclare) { final List declaredAttributes = new ArrayList<>(); final List createdInputs = attributesToDeclare.stream() @@ -111,10 +104,8 @@ public abstract class DefaultAttributeDeclarator declaredAttributes, - final ComponentInstanceAttribOutput attribOutput) { + private OutputDefinition declareAttributeOutput(final Component component, final PROPERTYOWNER propertiesOwner, + final List declaredAttributes, final ComponentInstanceAttribOutput attribOutput) { final AttributeDataDefinition attribute = resolveAttribute(declaredAttributes, attribOutput); final OutputDefinition outputDefinition = createOutput(component, propertiesOwner, attribOutput, attribute); final ATTRIBUTETYPE declaredAttribute = createDeclaredAttribute(attribute); @@ -124,40 +115,34 @@ public abstract class DefaultAttributeDeclarator attributesToCreate, - final ComponentInstanceAttribOutput attribOutput) { - final Optional resolvedAttribute = attributesToCreate.stream() - .filter(p -> p.getName().equals(attribOutput.getName())) + private AttributeDataDefinition resolveAttribute(final List attributesToCreate, final ComponentInstanceAttribOutput attribOutput) { + final Optional resolvedAttribute = attributesToCreate.stream().filter(p -> p.getName().equals(attribOutput.getName())) .findFirst(); return resolvedAttribute.isPresent() ? resolvedAttribute.get() : attribOutput; } - OutputDefinition createOutputFromAttribute(final String componentId, - final PROPERTYOWNER propertiesOwner, - final String outputName, - final ComponentInstanceAttribOutput attributeOutput, - final AttributeDataDefinition attribute) { + OutputDefinition createOutputFromAttribute(final String componentId, final PROPERTYOWNER propertiesOwner, final String outputName, + final ComponentInstanceAttribOutput attributeOutput, final AttributeDataDefinition attribute) { final String attributesName = attributeOutput.getAttributesName(); final AttributeDefinition selectedAttrib = attributeOutput.getOutput(); final String[] parsedAttribNames = attributeOutput.getParsedAttribNames(); @@ -207,7 +185,6 @@ public abstract class DefaultAttributeDeclarator mappedToscaTemplate = (Map) objValue; createOutputValue(mappedToscaTemplate, 1, parsedPropNames, outputName); - output.setValue(gson.toJson(mappedToscaTemplate)); } - } else { - jsonObject.put( - GET_ATTRIBUTE, Arrays.asList(output.getAttributes().get(0).getComponentInstanceName(), attributeDataDefinition.getName())); + jsonObject + .put(GET_ATTRIBUTE, Arrays.asList(output.getAttributes().get(0).getComponentInstanceName(), attributeDataDefinition.getName())); output.setValue(jsonObject.toJSONString()); } } - if (CollectionUtils.isEmpty(attributeDataDefinition.getGetOutputValues())) { attributeDataDefinition.setGetOutputValues(new ArrayList<>()); } final List getOutputValues = attributeDataDefinition.getGetOutputValues(); - final GetOutputValueDataDefinition getOutputValueDataDefinition = new GetOutputValueDataDefinition(); getOutputValueDataDefinition.setOutputId(output.getUniqueId()); getOutputValueDataDefinition.setOutputName(output.getName()); @@ -265,7 +235,6 @@ public abstract class DefaultAttributeDeclarator= 1) { if (i == parsedPropNames.length - 1) { final JSONObject jobProp = new JSONObject(); @@ -280,7 +249,6 @@ public abstract class DefaultAttributeDeclarator outputsToCreate; - private final List attributesToUpdate; - - AttributesDeclarationData(final List outputsToCreate, - final List attributesToUpdate) { - this.outputsToCreate = outputsToCreate; - this.attributesToUpdate = attributesToUpdate; - } - - List getOutputsToCreate() { - return outputsToCreate; - } - - List getAttributesToUpdate() { - return attributesToUpdate; - } - } - - Either prepareValueBeforeDelete(final OutputDefinition inputForDelete, - final AttributeDataDefinition inputValue, + Either prepareValueBeforeDelete(final OutputDefinition inputForDelete, final AttributeDataDefinition inputValue, final List pathOfComponentInstances) { final Either deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue); - // Either findDefaultValue = propertyOperation + // .findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), + // (String) inputValue.get_default()); + // if (findDefaultValue.isRight()) { + // deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils + // .convertFromStorageResponse( + // DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value())))); + // return deleteEither; + // + // } + // String defaultValue = findDefaultValue.left().value(); + // inputValue.set_default(defaultValue); + // log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); return deleteEither; } @@ -365,9 +323,7 @@ public abstract class DefaultAttributeDeclarator deleteEither = Either.left(outputForDelete); String value = outputValue.getValue(); final Map mappedToscaTemplate = (Map) new Yaml().load(value); - resetOutputName(mappedToscaTemplate, outputForDelete.getName()); - value = ""; if (MapUtils.isNotEmpty(mappedToscaTemplate)) { final Either result = cleanNestedMap(mappedToscaTemplate, true); @@ -380,11 +336,10 @@ public abstract class DefaultAttributeDeclarator getInputsValues = outputValue.getGetOutputValues(); if (getInputsValues != null && !getInputsValues.isEmpty()) { - final Optional op = - getInputsValues.stream().filter(gi -> gi.getOutputId().equals(outputForDelete.getUniqueId())).findAny(); + final Optional op = getInputsValues.stream() + .filter(gi -> gi.getOutputId().equals(outputForDelete.getUniqueId())).findAny(); op.ifPresent(getInputsValues::remove); } outputValue.setGetOutputValues(getInputsValues); @@ -410,9 +365,7 @@ public abstract class DefaultAttributeDeclarator outputsToCreate; + private final List attributesToUpdate; + + AttributesDeclarationData(final List outputsToCreate, final List attributesToUpdate) { + this.outputsToCreate = outputsToCreate; + this.attributesToUpdate = attributesToUpdate; + } + + List getOutputsToCreate() { + return outputsToCreate; + } + + List getAttributesToUpdate() { + return attributesToUpdate; + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/GetOutputUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/GetOutputUtils.java index 0565bc6c8f..e5d390a04e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/GetOutputUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/GetOutputUtils.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.attribute; import org.openecomp.sdc.be.datatypes.elements.GetOutputValueDataDefinition; @@ -28,7 +27,7 @@ public class GetOutputUtils { } public static boolean isGetOutputValueForOutput(GetOutputValueDataDefinition outputData, String outputId) { - return outputData.getOutputId().equals(outputId) - || (outputData.getGetOutputIndex() != null && outputData.getGetOutputIndex().getOutputId().equals(outputId)); + return outputData.getOutputId().equals(outputId) || (outputData.getGetOutputIndex() != null && outputData.getGetOutputIndex().getOutputId() + .equals(outputId)); } } 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 index 6bde6ba771..2ab68e8db1 100644 --- 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.csar; import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.FAILED_UPLOAD_ARTIFACT_TO_COMPONENT; @@ -50,12 +49,12 @@ import org.apache.commons.lang3.StringUtils; 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.artifact.ArtifactOperationInfo; import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; import org.openecomp.sdc.be.components.impl.CsarValidationUtils; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.ImportUtils; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; +import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; @@ -65,7 +64,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; 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.impl.ComponentsUtils; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; @@ -108,38 +106,32 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { private static final String ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME = "Artifact file is not in expected format, fileName {}"; private static final String ARTIFACT_INTERNALS_ARE_INVALID = "Artifact internals are invalid"; private static final String ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE = "Artifact with name {} and type {} already exist with type {}"; - private final Gson gson = new Gson(); private static final Pattern pattern = Pattern.compile("\\..(.*?)\\.."); private static final String LABEL_COUNTER_DELIMITER = "[^0-9]+"; protected final ArtifactsBusinessLogic artifactsBusinessLogic; + private final Gson gson = new Gson(); private final GroupBusinessLogic groupBusinessLogic; @Autowired - public CsarArtifactsAndGroupsBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsBusinessLogic artifactsBusinessLogic, ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public CsarArtifactsAndGroupsBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, + GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsBusinessLogic artifactsBusinessLogic, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.artifactsBusinessLogic = artifactsBusinessLogic; this.groupBusinessLogic = groupBusinessLogic; } - public Either createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, - String artifactsMetaFile, String artifactsMetaFileName, List createdArtifacts) { - + public Either createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, + String artifactsMetaFileName, List createdArtifacts) { log.debug("parseResourceArtifactsInfoFromFile start"); - return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName) - .left() - .bind( p-> createResourceArtifacts(csarInfo, resource, p, createdArtifacts)) - .right() - .map(rf -> { componentsUtils.auditResource(rf, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); return rf;}) - .left() - .bind(c -> checkoutRes(c)); + return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName).left() + .bind(p -> createResourceArtifacts(csarInfo, resource, p, createdArtifacts)).right().map(rf -> { + componentsUtils.auditResource(rf, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return rf; + }).left().bind(c -> checkoutRes(c)); } private Either checkoutRes(Component component) { @@ -149,33 +141,25 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { return checkoutRes1; } - public Either createResourceArtifactsFromCsar(CsarInfo csarInfo, Service resource, - String artifactsMetaFile, String artifactsMetaFileName, List createdArtifacts - ) { - + public Either createResourceArtifactsFromCsar(CsarInfo csarInfo, Service resource, String artifactsMetaFile, + String artifactsMetaFileName, List createdArtifacts) { log.debug("parseResourceArtifactsInfoFromFile start"); - return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName) - .left() - .bind(p -> createResourceArtifacts(csarInfo, resource, p, createdArtifacts)) - .right() - .map(rf -> rf) - .left() - .bind(c -> { - Either checkoutRes = getResourcetFromGraph(c); - Service resource1 = (Service) checkoutRes.left().value(); - Either checkoutRes1 = Either.left(resource1); - return checkoutRes1; - }); + return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName).left() + .bind(p -> createResourceArtifacts(csarInfo, resource, p, createdArtifacts)).right().map(rf -> rf).left().bind(c -> { + Either checkoutRes = getResourcetFromGraph(c); + Service resource1 = (Service) checkoutRes.left().value(); + Either checkoutRes1 = Either.left(resource1); + return checkoutRes1; + }); } - - public Either updateResourceArtifactsFromCsar(CsarInfo csarInfo, Component resource, - String artifactsMetaFile, String artifactsMetaFileName, List createdNewArtifacts, - boolean shouldLock, boolean inTransaction){ + public Either updateResourceArtifactsFromCsar(CsarInfo csarInfo, Component resource, String artifactsMetaFile, + String artifactsMetaFileName, + List createdNewArtifacts, boolean shouldLock, + boolean inTransaction) { Component updatedResource = resource; - Either>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile( - updatedResource, artifactsMetaFile, artifactsMetaFileName); + updatedResource, artifactsMetaFile, artifactsMetaFileName); if (parseResourceInfoFromYamlEither.isRight()) { ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); if (resource instanceof Resource) { @@ -183,135 +167,113 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } return Either.right(responseFormat); } - List groups = updatedResource.getGroups(); Map deploymentArtifact = updatedResource.getDeploymentArtifacts(); if (MapUtils.isEmpty(deploymentArtifact)) { deleteGroupsByType(groups, Constants.DEFAULT_GROUP_VF_MODULE, updatedResource); - return createResourceArtifacts(csarInfo, updatedResource, parseResourceInfoFromYamlEither.left().value(), - createdNewArtifacts); + return createResourceArtifacts(csarInfo, updatedResource, parseResourceInfoFromYamlEither.left().value(), createdNewArtifacts); } - - List createdDeploymentArtifactsAfterDelete = deploymentArtifact.values().stream() - .collect(Collectors.toList()); - - int labelCounter = createdDeploymentArtifactsAfterDelete - .stream() - .map(ArtifactDefinition::getArtifactLabel) - .filter(this::isLastCharacterInLabelADigit) - .map(this::getNextInt) - .flatMapToInt(this::toStream) - .max() - .orElse(-1) + 1; - + List createdDeploymentArtifactsAfterDelete = deploymentArtifact.values().stream().collect(Collectors.toList()); + int labelCounter = + createdDeploymentArtifactsAfterDelete.stream().map(ArtifactDefinition::getArtifactLabel).filter(this::isLastCharacterInLabelADigit) + .map(this::getNextInt).flatMapToInt(this::toStream).max().orElse(-1) + 1; ////////////////////////////////////// create set parsed + ////////////////////////////////////// artifacts/////////////////////////////////////////// Map> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value(); - List artifactsWithoutGroups = parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT); Collection> parsedArifactsCollection = parsedArtifactsMap.values(); - - Either>, ResponseFormat> parsedArtifactsPerGroupEither = createArtifactsTemplateCollection(csarInfo, updatedResource, createdNewArtifacts, - createdDeploymentArtifactsAfterDelete, labelCounter, parsedArifactsCollection); + Either>, ResponseFormat> parsedArtifactsPerGroupEither = createArtifactsTemplateCollection( + csarInfo, updatedResource, createdNewArtifacts, createdDeploymentArtifactsAfterDelete, 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, deploymentArtifact); - + Map>> groupArtifact = findMasterArtifactInGroup(groups, deploymentArtifact); ///////////////////////////////// find artifacts to - ///////////////////////////////// delete//////////////////////////////////////////////////// - + ///////////////////////////////// delete//////////////////////////////////////////////////// Map> groupToDelete = new HashMap<>(); Set artifactsToDelete = findArtifactThatNotInGroupToDelete(parsedGroup, createdDeploymentArtifactsAfterDelete); - Set jsonMasterArtifacts = parsedGroup.keySet(); - Map mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, - artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeploymentArtifactsAfterDelete); - + Map mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, + jsonMasterArtifacts, createdDeploymentArtifactsAfterDelete); List deletedArtifacts = new ArrayList<>(); - Either deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow( - updatedResource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete, deletedArtifacts); + 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 excludeDeletedArtifacts(deletedArtifacts, createdDeploymentArtifactsAfterDelete); - ////////////// dissociate, associate or create + ////////////// artifacts//////////////////////////// - Either assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, - updatedResource, createdNewArtifacts, labelCounter, - createdDeploymentArtifactsAfterDelete, mergedgroup, deletedArtifacts); + Either assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, updatedResource, createdNewArtifacts, + labelCounter, createdDeploymentArtifactsAfterDelete, 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(); deploymentArtifact = updatedResource.getDeploymentArtifacts(); - - createdDeploymentArtifactsAfterDelete = deploymentArtifact.values().stream() - .collect(Collectors.toList()); - + createdDeploymentArtifactsAfterDelete = deploymentArtifact.values().stream().collect(Collectors.toList()); // update vfModule names Set groupForAssociateWithMembers = mergedgroup.keySet(); - Either validateUpdateVfGroupNamesRes = updateVfModuleNames(createdNewArtifacts, - updatedResource, groups, createdDeploymentArtifactsAfterDelete, groupForAssociateWithMembers); - if (validateUpdateVfGroupNamesRes != null) return validateUpdateVfGroupNamesRes; - + Either validateUpdateVfGroupNamesRes = updateVfModuleNames(createdNewArtifacts, updatedResource, groups, + createdDeploymentArtifactsAfterDelete, groupForAssociateWithMembers); + if (validateUpdateVfGroupNamesRes != null) { + return validateUpdateVfGroupNamesRes; + } //////////////// create new artifacts in update + //////////////// flow//////////////////////////// List newArtifactsGroup = createNewArtifcats(parsedGroup, groupArtifact); - Either validateGroupNamesRes = handleArtifactsInGroup(csarInfo, createdNewArtifacts, - updatedResource, groups, createdDeploymentArtifactsAfterDelete, labelCounter, newArtifactsGroup); - if (validateGroupNamesRes != null) return validateGroupNamesRes; - + Either validateGroupNamesRes = handleArtifactsInGroup(csarInfo, createdNewArtifacts, updatedResource, groups, + createdDeploymentArtifactsAfterDelete, labelCounter, newArtifactsGroup); + if (validateGroupNamesRes != null) { + return validateGroupNamesRes; + } // updatedGroup Either updateVersionEither = updateGroupVersion(updatedResource, groupForAssociateWithMembers); - if (updateVersionEither != null) return updateVersionEither; + if (updateVersionEither != null) { + return updateVersionEither; + } if (!CollectionUtils.isEmpty(artifactsWithoutGroups)) { for (ArtifactTemplateInfo t : artifactsWithoutGroups) { List artifacts = new ArrayList<>(); artifacts.add(t); - Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, - artifacts, createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter); - if (checkResponse(resStatus)) return resStatus; + Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifacts, + createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter); + if (checkResponse(resStatus)) { + return resStatus; + } } - } - Either eitherGetResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId()); return mapResult(eitherGetResource, updatedResource); } private Either handleArtifactsInGroup(CsarInfo csarInfo, List createdNewArtifacts, - Component updatedResource, List groups, - List createdDeploymentArtifactsAfterDelete, - int labelCounter, List newArtifactsGroup) { + Component updatedResource, List groups, + List createdDeploymentArtifactsAfterDelete, int labelCounter, + List newArtifactsGroup) { if (!newArtifactsGroup.isEmpty()) { Collections.sort(newArtifactsGroup, ArtifactTemplateInfo::compareByGroupName); int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups); Either validateGroupNamesRes = groupBusinessLogic - .validateGenerateVfModuleGroupNames(newArtifactsGroup, updatedResource.getSystemName(), startGroupCounter); + .validateGenerateVfModuleGroupNames(newArtifactsGroup, updatedResource.getSystemName(), startGroupCounter); if (validateGroupNamesRes.isRight()) { return Either.right(validateGroupNamesRes.right().value()); } - Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, - newArtifactsGroup, createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter); - checkResponse(resStatus); + Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, newArtifactsGroup, + createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter); + checkResponse(resStatus); } return null; } @@ -320,10 +282,13 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { return (resStatus.isRight()); } - private Either updateVfModuleNames(List createdNewArtifacts, Component updatedResource, List groups, List createdDeploymentArtifactsAfterDelete, Set groupForAssociateWithMembers) { + private Either updateVfModuleNames(List createdNewArtifacts, Component updatedResource, + List groups, + List createdDeploymentArtifactsAfterDelete, + Set groupForAssociateWithMembers) { if (!CollectionUtils.isEmpty(groups)) { Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic - .validateUpdateVfGroupNamesOnGraph(groups, updatedResource); + .validateUpdateVfGroupNamesOnGraph(groups, updatedResource); if (validateUpdateVfGroupNamesRes.isRight()) { return Either.right(validateUpdateVfGroupNamesRes.right().value()); } @@ -334,17 +299,11 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { private Either updateGroupVersion(Component updatedResource, Set groupForAssociateWithMembers) { if (!groupForAssociateWithMembers.isEmpty()) { - - List groupsId = groupForAssociateWithMembers.stream() - .collect(Collectors.toList()); - - Either, ResponseFormat> updateVersionEither = groupBusinessLogic - .updateGroups(updatedResource, groupsId, true); + List groupsId = groupForAssociateWithMembers.stream().collect(Collectors.toList()); + Either, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(updatedResource, groupsId, true); if (updateVersionEither.isRight()) { log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value()); - return Either.right(updateVersionEither.right().value()); - } } return null; @@ -358,7 +317,7 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } private OptionalInt getNextInt(String artifactLabel) { - try(Scanner scanner = new Scanner(artifactLabel).useDelimiter(LABEL_COUNTER_DELIMITER)) { + try (Scanner scanner = new Scanner(artifactLabel).useDelimiter(LABEL_COUNTER_DELIMITER)) { if (scanner.hasNextInt()) { return OptionalInt.of(scanner.nextInt()); } @@ -367,44 +326,37 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } private boolean isLastCharacterInLabelADigit(String artifactLabel) { - return Character.isDigit(artifactLabel.charAt(artifactLabel.length()-1)); + return Character.isDigit(artifactLabel.charAt(artifactLabel.length() - 1)); } private Either mapResult(Either result, Component resource) { return result.right() - .map(status -> componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(status), resource)); + .map(status -> componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource)); } - - private void updateGroupMemebers(List groups, Set groupForAssociateWithMembers, List createdNewArtifacts, List createdDeploymentArtifactsAfterDelete) { + private void updateGroupMemebers(List groups, Set groupForAssociateWithMembers, + List createdNewArtifacts, List createdDeploymentArtifactsAfterDelete) { List heatGroups = collectGroupsWithMembers(groups); - for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) { Map members = new HashMap<>(); Set artifactsGroup = new HashSet<>(); artifactsGroup.addAll(updatedGroupDef.getArtifacts()); - associateMembersToArtifacts(createdNewArtifacts, createdDeploymentArtifactsAfterDelete, heatGroups, - artifactsGroup, members); - + associateMembersToArtifacts(createdNewArtifacts, createdDeploymentArtifactsAfterDelete, heatGroups, artifactsGroup, members); updatedGroupDef.setMembers(members); } } - /** * @param groups * @return */ private List collectGroupsWithMembers(List groups) { - return groups.stream() - .filter(e -> e.getMembers() != null) - .collect(Collectors.toList()); + return groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); } - /** * Exclude deleted Artificats from Deployment Artifcats + * * @param deletedArtifacts * @param createdDeploymentArtifactsAfterDelete */ @@ -420,30 +372,23 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { if (artToRemove != null) { createdDeploymentArtifactsAfterDelete.remove(artToRemove); } - } } - private void deleteGroupsByType(List groups, String groupType, Component resource) { - if(groups != null){ - List listToDelete = groups.stream() - .filter(g -> g.getType().equals(groupType)) - .collect(Collectors.toList()); - + if (groups != null) { + List listToDelete = groups.stream().filter(g -> g.getType().equals(groupType)).collect(Collectors.toList()); groupBusinessLogic.deleteGroups(resource, listToDelete); } } - - private List createNewArtifcats(Map> parsedGroup, Map>> groupArtifact) { + private List createNewArtifcats(Map> parsedGroup, + Map>> groupArtifact) { List newArtifactsGroup = new ArrayList<>(); - for (Entry> parsedGroupSetEntry : parsedGroup.entrySet()) { ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey(); boolean isNewGroup = true; - for (Entry>> groupListEntry : groupArtifact - .entrySet()) { + for (Entry>> groupListEntry : groupArtifact.entrySet()) { Map> groupArtifacts = groupListEntry.getValue(); Set group = groupArtifacts.keySet(); for (ArtifactDefinition artifactInfo : group) { @@ -456,64 +401,52 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { if (isNewGroup) { newArtifactsGroup.add(parsedArtifactMaster); } - } return newArtifactsGroup; } - private Set findArtifactThatNotInGroupToDelete( - Map> parsedGroup, - List createdDeploymentArtifactsAfterDelete) { + private Set findArtifactThatNotInGroupToDelete(Map> parsedGroup, + List createdDeploymentArtifactsAfterDelete) { 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 = createdDeploymentArtifactsAfterDelete.stream().filter(a -> a.getArtifactName().equalsIgnoreCase(template.getFileName())).findAny(); + if (template.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) { + Optional op = createdDeploymentArtifactsAfterDelete.stream() + .filter(a -> a.getArtifactName().equalsIgnoreCase(template.getFileName())).findAny(); if (op.isPresent() && !op.get().getArtifactType().equalsIgnoreCase(template.getType())) { artifactsToDelete.add(op.get()); } } } } - return artifactsToDelete; } - private Either createResourceArtifacts(CsarInfo csarInfo, Component resource, - Map> artifactsMap, - List createdArtifacts) { - + Map> artifactsMap, + List createdArtifacts) { Either resStatus = Either.left(resource); - Collection> arifactsCollection = artifactsMap.values(); - for (List groupTemplateList : arifactsCollection) { if (groupTemplateList != null) { - resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, - createdArtifacts, 0); + resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, createdArtifacts, 0); if (resStatus.isRight()) { return resStatus; } } } - return resStatus; - } - - private Either>, ResponseFormat> createArtifactsTemplateCollection( - CsarInfo csarInfo, Component resource, - List createdNewArtifacts, - List createdDeploymentArtifactsAfterDelete, int labelCounter, - Collection> parsedArifactsCollection) { - + private Either>, ResponseFormat> createArtifactsTemplateCollection(CsarInfo csarInfo, + Component resource, + List createdNewArtifacts, + List createdDeploymentArtifactsAfterDelete, + int labelCounter, + Collection> parsedArifactsCollection) { Map> parsedGroup = new HashMap<>(); - for (List parsedGroupTemplateList : parsedArifactsCollection) { - for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { if (parsedGroupTemplate.getGroupName() != null) { parsedGroupTemplate.setGroupName(""); @@ -527,64 +460,55 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } else { List arrtifacts = new ArrayList<>(); arrtifacts.add(parsedGroupTemplate); - Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, - resource, arrtifacts, createdNewArtifacts, createdDeploymentArtifactsAfterDelete, - labelCounter); + Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts, + createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter); if (resStatus.isRight()) { return Either.right(resStatus.right().value()); } - } } - } return Either.left(parsedGroup); } - @SuppressWarnings({ "unchecked", "static-access" }) - public Either>, ResponseFormat> parseResourceArtifactsInfoFromFile( - Component resource, String artifactsMetaFile, String artifactFileName) { - + @SuppressWarnings({"unchecked", "static-access"}) + public Either>, ResponseFormat> parseResourceArtifactsInfoFromFile(Component resource, + String artifactsMetaFile, + String artifactFileName) { 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_FORMAT_FILE_NAME, artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError( - ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); - return Either - .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + BeEcompErrorManager.getInstance() + .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID, + ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); } - Map>> artifactTemplateMap; artifactTemplateMap = ComponentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class); if (artifactTemplateMap.isEmpty()) { log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError( - ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); - return Either - .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + BeEcompErrorManager.getInstance() + .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + 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()){ + 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); + .validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter); if (validateGroupNamesRes.isRight()) { return Either.right(validateGroupNamesRes.right().value()); } @@ -592,36 +516,33 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } catch (Exception e) { log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName); log.debug("failed with exception.", e); - BeEcompErrorManager.getInstance().logInternalDataError( - ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + 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) { + private Either, ResponseFormat> parseArtifactTemplateList(String artifactFileName, + Map>> artifactTemplateMap, + List allGroups, + String artifactsTypeKey) { List> o = artifactTemplateMap.get(artifactsTypeKey); - Either, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule( - artifactsTypeKey, o); + Either, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o); if (artifactTemplateInfoListPairStatus.isRight()) { log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError( - ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + 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_FORMAT_FILE_NAME, artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError( - ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - + BeEcompErrorManager.getInstance() + .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + 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); @@ -630,30 +551,25 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } private Either, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, - List> jsonObject) { + List> jsonObject) { List artifactTemplateInfoList = new ArrayList<>(); for (Map o : jsonObject) { Either artifacttemplateInfoStatus = ArtifactTemplateInfo - .createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, - null); + .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, - Component resource, List artifactsTemplateList, - List createdArtifacts, int labelCounter) { + private Either createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource, + List artifactsTemplateList, + List createdArtifacts, int labelCounter) { List createdGroups = resource.getGroups(); List heatGroups = null; if (!CollectionUtils.isEmpty(createdGroups)) { @@ -664,57 +580,47 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { String groupName = groupTemplateInfo.getGroupName(); Set artifactsGroup = new HashSet<>(); Set artifactsUUIDGroup = new HashSet<>(); - log.debug("createDeploymentArtifactsFromCsar start"); Either resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, - artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter); + artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter); log.debug("createDeploymentArtifactsFromCsar end"); if (resStatus.isRight()) { return resStatus; } - Map createdArtifactsMap = createdArtifacts.stream().collect(Collectors.toMap( - ArtifactDataDefinition::getArtifactLabel, artifact -> artifact)); + Map createdArtifactsMap = createdArtifacts.stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, artifact -> artifact)); resource.setDeploymentArtifacts(createdArtifactsMap); if (groupName != null && !groupName.isEmpty()) { - Either groupDefinitionEither = buildGroupDefinition(createdArtifacts, heatGroups, groupTemplateInfo, - groupName, artifactsGroup, artifactsUUIDGroup); + groupName, artifactsGroup, artifactsUUIDGroup); if (groupDefinitionEither.isRight()) { return Either.right(groupDefinitionEither.right().value()); } needToCreate.add(groupDefinitionEither.left().value()); } } - Map createdArtifactsMap = createdArtifacts.stream().collect(Collectors.toMap( - ArtifactDataDefinition::getArtifactLabel, artifact -> artifact)); + Map createdArtifactsMap = createdArtifacts.stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, artifact -> artifact)); resource.setDeploymentArtifacts(createdArtifactsMap); - - Either, ResponseFormat> createGroups = groupBusinessLogic - .addGroups(resource, needToCreate, false); + Either, ResponseFormat> createGroups = groupBusinessLogic.addGroups(resource, needToCreate, false); if (createGroups.isRight()) { return Either.right(createGroups.right().value()); } - return Either.left(resource); } - private Either buildGroupDefinition(List createdArtifacts, - List heatGroups, ArtifactTemplateInfo groupTemplateInfo, String groupName, - Set artifactsGroup, Set artifactsUUIDGroup) { - + 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); } @@ -724,38 +630,34 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); properties.add(prop); Either getLatestGroupTypeRes = groupTypeOperation - .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); + .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); if (getLatestGroupTypeRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); } - properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, - createdArtifacts, artifactsList, getLatestGroupTypeRes.left().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, - Component resource, Set artifactsGroup, Set artifactsUUIDGroup, - ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, int labelCounter) { + private Either createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, Component resource, + Set artifactsGroup, Set artifactsUUIDGroup, + ArtifactTemplateInfo artifactTemplateInfo, + List createdArtifacts, int labelCounter) { Either resStatus = Either.left(resource); - String artifactUid = ""; String artifactEnvUid = ""; String artifactUUID = ""; - - // check if artifacts already exist Either createdArtifactEther = checkIfArtifactAlreadyExist(artifactTemplateInfo, createdArtifacts); - if(createdArtifactEther.isRight()){ + 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); + if (createdArtifact == null) { + Either newArtifactEither = createDeploymentArtifact(csarInfo, resource, artifactPath, + artifactTemplateInfo, createdArtifacts, labelCounter); if (newArtifactEither.isRight()) { resStatus = Either.right(newArtifactEither.right().value()); return resStatus; @@ -763,17 +665,14 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { ArtifactDefinition newArtifact = newArtifactEither.left().value(); artifactUid = newArtifact.getUniqueId(); artifactUUID = newArtifact.getArtifactUUID(); - final ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(newArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET - || artifactType == ArtifactTypeEnum.HEAT_VOL) { + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { ArtifactDefinition createHeatEnvPlaceHolder = artifactsBusinessLogic - .createHeatEnvPlaceHolder(createdArtifacts, newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, - resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), - csarInfo.getModifier(), resource, null); + .createHeatEnvPlaceHolder(createdArtifacts, newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), + NodeTypeEnum.Resource, resource.getName(), csarInfo.getModifier(), resource, null); artifactEnvUid = createHeatEnvPlaceHolder.getUniqueId(); } - }else{ + } else { artifactUid = createdArtifact.getUniqueId(); artifactUUID = createdArtifact.getArtifactUUID(); artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); @@ -783,12 +682,11 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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); + resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, + relatedArtifactTemplateInfo, createdArtifacts, labelCounter); if (resStatus.isRight()) { return resStatus; } @@ -800,171 +698,136 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) { String artifactEnvUid = ""; final ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(createdArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET - || artifactType == ArtifactTypeEnum.HEAT_VOL) { + 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){ - + 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()){ + 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_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, - artifactTemplateInfo.getType(), res.getArtifactType())); + 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_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID, + ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), res.getArtifactType())); } } return Either.left(res); - - } - private Either createDeploymentArtifact(CsarInfo csarInfo, Component resource, - String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, - int label) { + private Either createDeploymentArtifact(CsarInfo csarInfo, Component resource, String artifactPath, + ArtifactTemplateInfo artifactTemplateInfo, + List createdArtifacts, int label) { int updatedlabel = label; final String artifactFileName = artifactTemplateInfo.getFileName(); Either, ResponseFormat> artifactContentStatus = CsarValidationUtils - .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, - artifactFileName, componentsUtils); + .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils); if (artifactContentStatus.isRight()) { return Either.right(artifactContentStatus.right().value()); } updatedlabel += createdArtifacts.size(); - - Map json = ArtifactUtils.buildJsonForArtifact(artifactTemplateInfo, - artifactContentStatus.left().value().getValue(), updatedlabel, true); - - Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson( - resource, csarInfo.getModifier(), json, - new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE)); - + Map json = ArtifactUtils + .buildJsonForArtifact(artifactTemplateInfo, artifactContentStatus.left().value().getValue(), updatedlabel, true); + Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, + csarInfo.getModifier(), json, 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); + 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(Component resource, CsarInfo csarInfo, - ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) { - + ArtifactTemplateInfo artifactTemplateInfo, + ArtifactDefinition currentInfo, boolean isUpdateEnv) { Component updatedResource = resource; Either resStatus = Either.left(currentInfo); if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) { - Either, ResponseFormat> artifactParamsStatus = CsarValidationUtils - .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), - CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(), - componentsUtils); + .getArtifactContent(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); - + 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) { Map artifacts = updatedResource.getDeploymentArtifacts(); - Optional op = artifacts.values().stream().filter( - p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())) - .findAny(); + Optional op = artifacts.values().stream() + .filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny(); if (op.isPresent()) { ArtifactDefinition artifactInfoHeatEnv = op.get(); artifactInfoHeatEnv.setHeatParamUpdated(true); Either updateArtifactOnResource = artifactToscaOperation - .updateArtifactOnResource(artifactInfoHeatEnv, updatedResource, - artifactInfoHeatEnv.getUniqueId(), null, null,true); + .updateArtifactOnResource(artifactInfoHeatEnv, updatedResource, artifactInfoHeatEnv.getUniqueId(), null, null, true); if (updateArtifactOnResource.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(updateArtifactOnResource.right().value()))); + 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(updateArtifactOnResource.right().value()))); } - resource.getDeploymentArtifacts().put(updateArtifactOnResource.left().value().getArtifactLabel(), updateArtifactOnResource.left().value()); + resource.getDeploymentArtifacts() + .put(updateArtifactOnResource.left().value().getArtifactLabel(), updateArtifactOnResource.left().value()); resStatus = Either.left(updateArtifactOnResource.left().value()); } - } return resStatus; } - private Either, ResponseFormat> extractHeatParameters(String artifactType, - String fileName, byte[] content, boolean is64Encoded) { + 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); + .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", + 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.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName)); } return Either.left(heatParameters.left().value()); - } - private Either updateHeatParams(Component resource, - ArtifactDefinition currentInfo, List updatedHeatEnvParams) { - + private Either updateHeatParams(Component resource, ArtifactDefinition currentInfo, + List updatedHeatEnvParams) { Either resStatus = Either.left(currentInfo); List currentHeatEnvParams = currentInfo.getListHeatParameters(); - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null - && !currentHeatEnvParams.isEmpty()) { - + 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(); @@ -972,28 +835,24 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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); + 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)); - + currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); break; } } } currentInfo.setListHeatParameters(currentHeatEnvParams); Either updateArtifactOnResource = artifactToscaOperation - .updateArtifactOnResource(currentInfo, resource, currentInfo.getUniqueId(), - null, null, true); + .updateArtifactOnResource(currentInfo, resource, currentInfo.getUniqueId(), null, null, true); if (updateArtifactOnResource.isRight()) { - log.debug( - "Failed to update heat parameters of heat on CSAR flow for component {} artifact {} label {}", - resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel()); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(updateArtifactOnResource.right().value()))); + log.debug("Failed to update heat parameters of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), + currentInfo.getUniqueId(), currentInfo.getArtifactLabel()); + return Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArtifactOnResource.right().value()))); } resource.getDeploymentArtifacts().put(currentInfo.getArtifactLabel(), currentInfo); resStatus = Either.left(updateArtifactOnResource.left().value()); @@ -1001,17 +860,15 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { return resStatus; } - public Either, ResponseFormat> createOrUpdateCsarArtifactFromJson( - Component component, User user, Map json, ArtifactOperationInfo operation) { - + public Either, ResponseFormat> createOrUpdateCsarArtifactFromJson(Component component, User user, + Map json, + ArtifactOperationInfo operation) { String jsonStr = gson.toJson(json); - ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, - ArtifactDefinition.class, false); - + ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class, false); Either result; try { - result = artifactsBusinessLogic.handleLoadedArtifact( - component, user, operation, false, true, component.getComponentType(), artifactDefinitionFromJson); + result = artifactsBusinessLogic + .handleLoadedArtifact(component, user, operation, false, true, component.getComponentType(), artifactDefinitionFromJson); } catch (ComponentException e) { log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, component.getComponentType(), component.getName()); return Either.right(componentsUtils.getResponseFormat(e)); @@ -1023,9 +880,8 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { return Either.left(result); } - private void associateMembersToArtifacts(List createdArtifacts, - List artifactsFromResource, List heatGroups, - Set artifactsGroup, Map members) { + 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(); @@ -1036,9 +892,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } } - 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(); + 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(); @@ -1047,26 +904,22 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } List artifacts = new ArrayList<>(); for (String artifactId : artifactsGroup) { - Optional opArt = createdArtifacts.stream() - .filter(p -> p.getUniqueId().equals(artifactId)).findAny(); + Optional opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny(); opArt.ifPresent(artifacts::add); if (artifactsFromResource != null) { - opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)) - .findAny(); + opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny(); opArt.ifPresent(artifacts::add); } } - Optional resOp = artifacts.stream() - .filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny(); + Optional resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny(); resOp.ifPresent(artifactDefinition -> 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(); + 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()); @@ -1078,13 +931,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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)); @@ -1093,15 +943,13 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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())) { + if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { isVolume = true; break; } @@ -1113,11 +961,8 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { return properties; } - private void mergeWithGroupTypeProperties(List properties, - List groupTypeProperties) { - - Map propertiesMap = properties.stream() - .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); + private void mergeWithGroupTypeProperties(List properties, List groupTypeProperties) { + Map propertiesMap = properties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); for (PropertyDefinition groupTypeProperty : groupTypeProperties) { if (!propertiesMap.containsKey(groupTypeProperty.getName())) { properties.add(new GroupProperty(groupTypeProperty)); @@ -1126,50 +971,53 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } private Map mergeGroupInUpdateFlow( - Map>> groupArtifact, - Map> parsedGroup, Set artifactsToDelete, - Map> groupToDelete, Set jsonMasterArtifacts, - List createdDeploymentArtifacts) { + Map>> groupArtifact, + Map> parsedGroup, Set artifactsToDelete, + Map> groupToDelete, Set jsonMasterArtifacts, + List createdDeploymentArtifacts) { Map mergedgroup = new HashMap<>(); - for (Entry>> groupListEntry : groupArtifact - .entrySet()) { + for (Entry>> groupListEntry : groupArtifact.entrySet()) { Map> createdArtifactMap = groupListEntry.getValue(); boolean isNeedToDeleteGroup = true; List listToDelete = null; for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) { - listToDelete = prepareArtifactsToDelete(parsedGroup, artifactsToDelete, createdDeploymentArtifacts, createdArtifactMap, maserArtifact); + listToDelete = prepareArtifactsToDelete(parsedGroup, artifactsToDelete, createdDeploymentArtifacts, createdArtifactMap, + maserArtifact); if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) { GroupDefinition group = groupListEntry.getKey(); deleteArtifacts(artifactsToDelete, group); - } - for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) { - isNeedToDeleteGroup = isNeedToDeleteGroup(mergedgroup, groupListEntry, createdArtifactMap, isNeedToDeleteGroup, maserArtifact, jsonMasterArtifact); + isNeedToDeleteGroup = isNeedToDeleteGroup(mergedgroup, groupListEntry, createdArtifactMap, isNeedToDeleteGroup, maserArtifact, + jsonMasterArtifact); } - } if (isNeedToDeleteGroup) { groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete); } - } return mergedgroup; } - private boolean isNeedToDeleteGroup(Map mergedgroup, Entry>> groupListEntry, Map> createdArtifactMap, boolean isNeedToDeleteGroup, ArtifactDefinition maserArtifact, ArtifactTemplateInfo jsonMasterArtifact) { + private boolean isNeedToDeleteGroup(Map mergedgroup, + Entry>> groupListEntry, + Map> createdArtifactMap, boolean isNeedToDeleteGroup, + ArtifactDefinition maserArtifact, ArtifactTemplateInfo jsonMasterArtifact) { 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; - } return isNeedToDeleteGroup; } - private List prepareArtifactsToDelete(Map> parsedGroup, Set artifactsToDelete, List createdDeploymentArtifacts, Map> createdArtifactMap, ArtifactDefinition maserArtifact) { + private List prepareArtifactsToDelete(Map> parsedGroup, + Set artifactsToDelete, + List createdDeploymentArtifacts, + Map> createdArtifactMap, + ArtifactDefinition maserArtifact) { List listToDelete; listToDelete = createdArtifactMap.get(maserArtifact); for (ArtifactDefinition artToDelete : listToDelete) { @@ -1180,92 +1028,76 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { private void deleteArtifacts(Set artifactsToDelete, GroupDefinition group) { for (ArtifactDefinition artifactDefinition : artifactsToDelete) { - if (CollectionUtils.isNotEmpty(group.getArtifacts()) - && group.getArtifacts().contains(artifactDefinition.getUniqueId())) { + 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())) { + if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) { group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID()); - } } } - private void findArtifactToDelete(Map> parsedGroup, - Set artifactsToDelete, ArtifactDefinition artifact, - List createdDeploymentArtifacts) { + private void findArtifactToDelete(Map> parsedGroup, Set artifactsToDelete, + ArtifactDefinition artifact, List createdDeploymentArtifacts) { boolean isNeedToDeleteArtifact = true; String artifactType = artifact.getArtifactType(); ArtifactDefinition generatedFromArt = null; if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) { - Optional op = createdDeploymentArtifacts.stream() - .filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny(); + Optional op = createdDeploymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())) + .findAny(); if (op.isPresent()) { generatedFromArt = op.get(); } - } - isNeedToDeleteArtifact(parsedGroup, artifactsToDelete, artifact, isNeedToDeleteArtifact, artifactType, generatedFromArt); } - private void isNeedToDeleteArtifact(Map> parsedGroup, Set - artifactsToDelete, ArtifactDefinition artifact, boolean isNeedToDeleteArtifact, String artifactType, ArtifactDefinition generatedFromArt) { - + private void isNeedToDeleteArtifact(Map> parsedGroup, Set artifactsToDelete, + ArtifactDefinition artifact, boolean isNeedToDeleteArtifact, String artifactType, + ArtifactDefinition generatedFromArt) { for (Entry> parsedGroupSetEntry : parsedGroup.entrySet()) { Set artifactsNames = parsedGroupSetEntry.getValue(); for (ArtifactTemplateInfo template : artifactsNames) { - if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) - && artifactType.equalsIgnoreCase(template.getType())) { + if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) { isNeedToDeleteArtifact = false; break; } else { - if (generatedFromArt != null - && generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) - && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) { - isNeedToDeleteArtifact = false; - break; + if (generatedFromArt != null && generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt + .getArtifactType().equalsIgnoreCase(template.getType())) { + isNeedToDeleteArtifact = false; + break; } } } - } if (isNeedToDeleteArtifact) { artifactsToDelete.add(artifact); - } } - private Map>> findMasterArtifactInGroup( - List groups, Map deploymentArtifact) { + private Map>> findMasterArtifactInGroup(List groups, + Map deploymentArtifact) { 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(deploymentArtifact, artifacts, - artifactsList); + ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deploymentArtifact, artifacts, artifactsList); if (masterArtifact != null) { gupsMap.put(masterArtifact, artifacts); } groupArtifact.put(group, gupsMap); - } } return groupArtifact; } - private Either deleteArtifactsInUpdateCsarFlow(Component resource, - User user, boolean shouldLock, boolean inTransaction, Set artifactsToDelete, - Map> groupToDelete, List deletedArtifacts) { - + private Either deleteArtifactsInUpdateCsarFlow(Component resource, User user, boolean shouldLock, + boolean inTransaction, Set artifactsToDelete, + Map> groupToDelete, + List deletedArtifacts) { Component updatedResource = resource; - String resourceId = updatedResource.getUniqueId(); if (!artifactsToDelete.isEmpty()) { for (ArtifactDefinition artifact : artifactsToDelete) { @@ -1273,16 +1105,12 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { final ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.parse(artifactType); if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) { Either handleDelete = artifactsBusinessLogic - .handleDelete(resourceId, artifact.getUniqueId(), user, - updatedResource, shouldLock, inTransaction); - + .handleDelete(resourceId, artifact.getUniqueId(), user, updatedResource, shouldLock, inTransaction); if (handleDelete.isRight()) { return Either.right(handleDelete.right().value()); } - deletedArtifacts.add(handleDelete.left().value()); } - } } if (!groupToDelete.isEmpty()) { @@ -1290,12 +1118,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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(); + 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); @@ -1305,23 +1131,19 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } } List oldGroups = updatedResource.getGroups(); - Either eitherGerResource = toscaOperationFacade - .getToscaElement(updatedResource.getUniqueId()); + Either eitherGerResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId()); if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource, resource.getComponentType()); - + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource, + resource.getComponentType()); return Either.right(responseFormat); - } updatedResource = eitherGerResource.left().value(); updatedResource.setGroups(oldGroups); return Either.left(updatedResource); } - private void createArtifactsGroupSet(List parsedGroupTemplateList, - Set parsedArtifactsName) { - + private void createArtifactsGroupSet(List parsedGroupTemplateList, Set parsedArtifactsName) { for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { parsedArtifactsName.add(parsedGroupTemplate); List relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); @@ -1331,68 +1153,58 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } } - private Either createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, - Component resource, List artifactsTemplateList, - List createdNewArtifacts, List artifactsFromResource, - int labelCounter) { - + private Either createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource, + List artifactsTemplateList, + List createdNewArtifacts, + List artifactsFromResource, + int labelCounter) { Component updatedResource = resource; - Either resStatus = Either.left(updatedResource); List createdGroups = updatedResource.getGroups(); List heatGroups = null; if (createdGroups != null && !createdGroups.isEmpty()) { heatGroups = collectGroupsWithMembers(createdGroups); } - 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); + resStatus = createDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, + createdNewArtifacts, artifactsFromResource, labelCounter); if (resStatus.isRight()) { return resStatus; } if (!StringUtils.isEmpty(groupName)) { Map members = new HashMap<>(); - associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, - members); - + 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); + .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); if (getLatestGroupTypeRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); + return Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); } - properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, - createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); + properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, + getLatestGroupTypeRes.left().value()); groupDefinition.convertFromGroupProperties(properties); - needToAdd.add(groupDefinition); } } @@ -1401,32 +1213,30 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnoreArtifacts(false); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreComponentInstances(false); - Either component = toscaOperationFacade - .getToscaElement(updatedResource.getUniqueId(), componentParametersView); + .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, false); + Either, ResponseFormat> addGroups = groupBusinessLogic.addGroups(updatedResource, needToAdd, false); if (addGroups.isRight()) { return Either.right(addGroups.right().value()); } - return resStatus; } - private Either createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource, - Set artifactsGroup, Set artifactsUUIDGroup, ArtifactTemplateInfo artifactTemplateInfo, - List createdArtifacts, List artifactsFromResource, int labelCounter) { + private Either createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource, Set artifactsGroup, + Set artifactsUUIDGroup, + ArtifactTemplateInfo artifactTemplateInfo, + List createdArtifacts, + List artifactsFromResource, int labelCounter) { 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) { @@ -1434,51 +1244,44 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + 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_FORMAT_FILE_NAME + artifactFileName, + ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_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_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + 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_FORMAT_FILE_NAME + artifactFileName, + ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_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); + Either newArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, + artifactTemplateInfo, createdArtifacts, labelCounter); if (newArtifactEither.isRight()) { resStatus = Either.right(newArtifactEither.right().value()); return resStatus; @@ -1487,27 +1290,23 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { artifactUid = newArtifact.getUniqueId(); artifactUUID = newArtifact.getArtifactUUID(); final ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(newArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET - || artifactType == ArtifactTypeEnum.HEAT_VOL) { + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { ArtifactDefinition createHeatEnvPlaceHolder = artifactsBusinessLogic - .createHeatEnvPlaceHolder(createdArtifacts, newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, - resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), - csarInfo.getModifier(), resource, null); + .createHeatEnvPlaceHolder(createdArtifacts, newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), + NodeTypeEnum.Resource, resource.getName(), csarInfo.getModifier(), resource, null); artifactEnvUid = createHeatEnvPlaceHolder.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); + resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, + createdArtifacts, artifactsFromResource, labelCounter); if (resStatus.isRight()) { return resStatus; } @@ -1516,16 +1315,16 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { return resStatus; } - private Either associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, - Component resource, List createdNewArtifacts, int labelCounter, - List createdDeploymentArtifactsAfterDelete, - Map mergedgroup, List deletedArtifacts) { + private Either associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, Component resource, + List createdNewArtifacts, int labelCounter, + List createdDeploymentArtifactsAfterDelete, + Map mergedgroup, + List deletedArtifacts) { Map> artifactsToAssotiate = new HashMap<>(); Map>> artifactsToUpdateMap = new HashMap<>(); Either resEither; for (Entry entry : mergedgroup.entrySet()) { - List dissArtifactsInGroup = entry.getValue() - .getListToDissotiateArtifactFromGroup(deletedArtifacts); + List dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts); GroupDefinition grDef = entry.getKey(); if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) { for (ArtifactDefinition art : dissArtifactsInGroup) { @@ -1533,70 +1332,63 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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(); + 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(); + .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()); + 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())) { + 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(); + .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 : createdDeploymentArtifactsAfterDelete) { @@ -1608,17 +1400,13 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { if (!heatEnvId.isEmpty()) { arifactsUids.add(heatEnvId); Optional op = createdDeploymentArtifactsAfterDelete.stream() - .filter(p -> p.getUniqueId().equals(heatEnvId)).findAny(); + .filter(p -> p.getUniqueId().equals(heatEnvId)).findAny(); if (op.isPresent()) { - this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource, - resource.getComponentType().getNodeType()); - + this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource, resource.getComponentType().getNodeType()); } } - break; } - } if (isCreate) { // check if already created for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) { @@ -1634,10 +1422,9 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } } } - if (isCreate) { - Either createArtifactEither = createDeploymentArtifact(csarInfo, - resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter); + Either createArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, + artifactTemplate, createdNewArtifacts, labelCounter); if (createArtifactEither.isRight()) { resEither = Either.right(createArtifactEither.right().value()); return resEither; @@ -1647,16 +1434,14 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { arifactsUuids.add(createdArtifact.getArtifactUUID()); final ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(createdArtifact.getArtifactType()); if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET - || artifactType == ArtifactTypeEnum.HEAT_VOL) { + || artifactType == ArtifactTypeEnum.HEAT_VOL) { ArtifactDefinition createHeatEnvPlaceHolder = artifactsBusinessLogic - .createHeatEnvPlaceHolder(new ArrayList<>(), createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, - resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), - csarInfo.getModifier(), resource, null); + .createHeatEnvPlaceHolder(new ArrayList<>(), createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, + resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), csarInfo.getModifier(), resource, null); String heatEnvId = createHeatEnvPlaceHolder.getUniqueId(); arifactsUids.add(heatEnvId); } } - } if (arifactsUids != null && !arifactsUids.isEmpty()) { List artifactsToAssociate = new ArrayList<>(); @@ -1666,86 +1451,71 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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); - + Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource, resource.getComponentType()); - + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource, + resource.getComponentType()); resEither = Either.right(responseFormat); return resEither; - } resEither = Either.left(eitherGerResource.left().value()); return resEither; } - private Either updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, - Component resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo, - List updatedArtifacts, List updatedRequiredArtifacts) { - + private Either updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource, + ArtifactDefinition oldArtifact, + ArtifactTemplateInfo artifactTemplateInfo, + List updatedArtifacts, + List updatedRequiredArtifacts) { 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_FORMAT_FILE_NAME + artifactFileName, - ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + 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_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID, + ErrorSeverity.ERROR); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType())); } return Either.left(updatedArtifact); } - } - Either, ResponseFormat> artifactContententStatus = CsarValidationUtils - .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), - CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils); + .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, + componentsUtils); if (artifactContententStatus.isRight()) { return Either.right(artifactContententStatus.right().value()); } - - Map json = ArtifactUtils.buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, - oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), - oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(), + 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, - new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE)); - + Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, + csarInfo.getModifier(), json, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE)); if (uploadArtifactToService.isRight()) { return Either.right(uploadArtifactToService.right().value()); } ArtifactDefinition previousInfo = uploadArtifactToService.left().value().left().value(); ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); updatedArtifacts.add(currentInfo); - - Either updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, - artifactTemplateInfo, currentInfo, true); - + Either updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, + true); if (updateEnvEither.isRight()) { log.debug("failed to update parameters to artifact {}", artifactFileName); return Either.right(updateEnvEither.right().value()); } - artifactsBusinessLogic.updateGroupForHeat(previousInfo, updateEnvEither.left().value(), resource); - updatedArtifacts.add(updateEnvEither.left().value()); return Either.left(currentInfo); } @@ -1753,31 +1523,28 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { 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.isEmpty()){ - for(GroupDefinition gr : vfGroupsToDelete){ + if (groupsToDelete != null && !groupsToDelete.isEmpty()) { + List vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) + .collect(Collectors.toList()); + if (!vfGroupsToDelete.isEmpty()) { + for (GroupDefinition gr : vfGroupsToDelete) { List artifacts = gr.getArtifacts(); for (String artifactId : artifacts) { - Either handleDelete = - artifactsBusinessLogic.handleDelete( - updatedResource.getUniqueId(), artifactId, csarInfo.getModifier(), - updatedResource, shouldLock, inTransaction); + Either handleDelete = artifactsBusinessLogic + .handleDelete(updatedResource.getUniqueId(), artifactId, csarInfo.getModifier(), 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); - + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), updatedResource); return Either.right(responseFormat); - } updatedResource = eitherGetResource.left().value(); } @@ -1789,8 +1556,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { Service 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()); - Either eitherGetResource = deleteVfGroups(vfGroupsToDelete, updatedResource, csarInfo, shouldLock, inTransaction); + List vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) + .collect(Collectors.toList()); + Either eitherGetResource = deleteVfGroups(vfGroupsToDelete, updatedResource, csarInfo, shouldLock, + inTransaction); if (eitherGetResource.isRight()) { return Either.right(eitherGetResource.right().value()); } @@ -1799,14 +1568,15 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { return Either.left(updatedResource); } - private Either deleteVfGroups(List vfGroupsToDelete, Service resource, CsarInfo csarInfo, boolean shouldLock, boolean inTransaction) { + private Either deleteVfGroups(List vfGroupsToDelete, Service resource, CsarInfo csarInfo, + boolean shouldLock, boolean inTransaction) { ResponseFormat responseFormat; if (vfGroupsToDelete != null && !vfGroupsToDelete.isEmpty()) { for (GroupDefinition gr : vfGroupsToDelete) { List artifacts = gr.getArtifacts(); for (String artifactId : artifacts) { - Either handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), - resource, shouldLock, inTransaction); + Either handleDelete = artifactsBusinessLogic + .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), resource, shouldLock, inTransaction); if (handleDelete.isRight()) { log.debug("Couldn't delete artifact {}", artifactId); return Either.right(handleDelete.right().value()); @@ -1814,11 +1584,11 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { } } groupBusinessLogic.deleteGroups(resource, vfGroupsToDelete); - Either eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (eitherGetResource.isRight()) { - responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource, resource.getComponentType()); - + responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource, + resource.getComponentType()); return Either.right(responseFormat); } resource = eitherGetResource.left().value(); @@ -1828,14 +1598,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { return Either.right(responseFormat); } - private Either getResourcetFromGraph(Component component) { log.debug("getResource start"); - return toscaOperationFacade.getToscaElement(component.getUniqueId()) - .right() - .map(rf -> componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(rf), component, component.getComponentType())) - .left() - .map(c -> c); + return toscaOperationFacade.getToscaElement(component.getUniqueId()).right().map(rf -> componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(rf), component, component.getComponentType())).left() + .map(c -> c); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogic.java index 51199e62a9..6f530ccd3a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogic.java @@ -22,6 +22,7 @@ package org.openecomp.sdc.be.components.csar; import fj.data.Either; +import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; import org.openecomp.sdc.be.components.impl.CsarValidationUtils; @@ -51,31 +52,22 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.Map; - @org.springframework.stereotype.Component("csarBusinessLogic") public class CsarBusinessLogic extends BaseBusinessLogic { private static final Logger log = Logger.getLogger(CsarBusinessLogic.class); - private static final String CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID = "Creating resource from CSAR: fetching CSAR with id "; private static final String FAILED = " failed"; - private final YamlTemplateParsingHandler yamlHandler; private CsarOperation csarOperation; @Autowired - public CsarBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - YamlTemplateParsingHandler yamlHandler, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public CsarBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, YamlTemplateParsingHandler yamlHandler, + ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.yamlHandler = yamlHandler; } @@ -86,121 +78,100 @@ public class CsarBusinessLogic extends BaseBusinessLogic { public void validateCsarBeforeCreate(Resource resource, AuditingActionEnum auditingAction, User user, String csarUUID) { // check if VF with the same Csar UUID or with he same name already + // exists StorageOperationStatus status = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID); - if(status == StorageOperationStatus.ENTITY_ALREADY_EXISTS){ - log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", - resource.getSystemName(), csarUUID); - auditAndThrowException(resource, user, auditingAction, ActionStatus.VSP_ALREADY_EXISTS, - csarUUID); + if (status == StorageOperationStatus.ENTITY_ALREADY_EXISTS) { + log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID); + auditAndThrowException(resource, user, auditingAction, ActionStatus.VSP_ALREADY_EXISTS, csarUUID); } else if (status != StorageOperationStatus.OK) { - log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, - resource.getSystemName()); + log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName()); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); } } public void validateCsarBeforeCreate(Service resource, String csarUUID) { // check if VF with the same Csar UUID or with he same name already + // exists StorageOperationStatus status = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID); log.debug("enter validateCsarBeforeCreate,get status:{}", status); if (status == StorageOperationStatus.ENTITY_ALREADY_EXISTS) { - log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", - resource.getSystemName(), csarUUID); + log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID); } else if (status != StorageOperationStatus.OK) { - log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, - resource.getSystemName()); + log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName()); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); } } - public CsarInfo getCsarInfo(Resource resource, Resource oldResource,User user, Map payload, String csarUUID){ + public CsarInfo getCsarInfo(Resource resource, Resource oldResource, User user, Map payload, String csarUUID) { Map csar = getCsar(resource, user, payload, csarUUID); - ImmutablePair toscaYamlCsarStatus = validateAndParseCsar(resource, - user, csar, csarUUID) - .left().on(this::throwComponentException); - - String checksum = CsarValidationUtils.getToscaYamlChecksum(csar, - csarUUID, componentsUtils).left().on(r->logAndThrowComponentException(r, "Failed to calculate checksum for casrUUID {} error {} ", csarUUID)); - if (oldResource!=null && !checksum.equals( - oldResource.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, - oldResource.getComponentMetadataDefinition().getMetadataDataDefinition() - .getImportedToscaChecksum(), - checksum); - oldResource.getComponentMetadataDefinition().getMetadataDataDefinition() - .setImportedToscaChecksum(checksum); + ImmutablePair toscaYamlCsarStatus = validateAndParseCsar(resource, user, csar, csarUUID).left() + .on(this::throwComponentException); + String checksum = CsarValidationUtils.getToscaYamlChecksum(csar, csarUUID, componentsUtils).left() + .on(r -> logAndThrowComponentException(r, "Failed to calculate checksum for casrUUID {} error {} ", csarUUID)); + if (oldResource != null && !checksum + .equals(oldResource.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, oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum); + oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum); } - - return new CsarInfo(user, csarUUID, csar, resource.getName(), - toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true); + return new CsarInfo(user, csarUUID, csar, resource.getName(), toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true); } - public CsarInfo getCsarInfo(Service service, Service oldResource,User user, Map payload, String csarUUID){ + public CsarInfo getCsarInfo(Service service, Service oldResource, User user, Map payload, String csarUUID) { Map csar = getCsar(service, user, payload, csarUUID); - ImmutablePair toscaYamlCsarStatus = validateAndParseCsar(service, - user, csar, csarUUID) - .left().on(this::throwComponentException); - - String checksum = CsarValidationUtils.getToscaYamlChecksum(csar, - csarUUID, componentsUtils).left().on(r->logAndThrowComponentException(r, "Failed to calculate checksum for casrUUID {} error {} ", csarUUID)); - if (oldResource!=null && !checksum.equals( - oldResource.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, - oldResource.getComponentMetadataDefinition().getMetadataDataDefinition() - .getImportedToscaChecksum(), - checksum); - oldResource.getComponentMetadataDefinition().getMetadataDataDefinition() - .setImportedToscaChecksum(checksum); + ImmutablePair toscaYamlCsarStatus = validateAndParseCsar(service, user, csar, csarUUID).left() + .on(this::throwComponentException); + String checksum = CsarValidationUtils.getToscaYamlChecksum(csar, csarUUID, componentsUtils).left() + .on(r -> logAndThrowComponentException(r, "Failed to calculate checksum for casrUUID {} error {} ", csarUUID)); + if (oldResource != null && !checksum + .equals(oldResource.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, oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum); + oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum); } - - return new CsarInfo(user, csarUUID, csar, service.getName(), - toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true); + return new CsarInfo(user, csarUUID, csar, service.getName(), toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true); } - - public ParsedToscaYamlInfo getParsedToscaYamlInfo(String topologyTemplateYaml, String yamlName, Map nodeTypesInfo, CsarInfo csarInfo, String nodeName, Component component) { - return yamlHandler.parseResourceInfoFromYAML( - yamlName, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, - nodeName, component); + + public ParsedToscaYamlInfo getParsedToscaYamlInfo(String topologyTemplateYaml, String yamlName, Map nodeTypesInfo, + CsarInfo csarInfo, String nodeName, Component component) { + return yamlHandler + .parseResourceInfoFromYAML(yamlName, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName, + component); } - private String logAndThrowComponentException(ResponseFormat responseFormat, String logMessage, String ...params) { + private String logAndThrowComponentException(ResponseFormat responseFormat, String logMessage, String... params) { log.debug(logMessage, params, responseFormat); throw new ByResponseFormatComponentException(responseFormat); } - private ImmutablePair throwComponentException(ResponseFormat responseFormat) { + private ImmutablePair throwComponentException(ResponseFormat responseFormat) { throw new ByResponseFormatComponentException(responseFormat); } - private Either, ResponseFormat> validateAndParseCsar(Component component, User user, - Map payload, String csarUUID) { + private Either, ResponseFormat> validateAndParseCsar(Component component, User user, Map payload, + String csarUUID) { Map csar = getCsar(component, user, payload, csarUUID); - Either validateCsarStatus = CsarValidationUtils.validateCsar(csar, - csarUUID, componentsUtils); + Either validateCsarStatus = CsarValidationUtils.validateCsar(csar, 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); - if(component instanceof Resource){ - componentsUtils.auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.CREATE_RESOURCE); + BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED); + if (component instanceof Resource) { + componentsUtils.auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.CREATE_RESOURCE); } - return Either.right(responseFormat); } - - Either, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils - .getToscaYaml(csar, csarUUID, componentsUtils); - + Either, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar, 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); - if(component instanceof Resource) { - componentsUtils.auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.CREATE_RESOURCE); + BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED); + if (component instanceof Resource) { + componentsUtils.auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.CREATE_RESOURCE); } return Either.right(responseFormat); } @@ -215,48 +186,38 @@ public class CsarBusinessLogic extends BaseBusinessLogic { if (csar.isRight()) { StorageOperationStatus value = csar.right().value(); log.debug("#getCsar - failed to fetch 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); - if(component instanceof Resource){ + BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID); + if (component instanceof Resource) { Resource newResource = (Resource) component; componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.CREATE_RESOURCE); } - throw new StorageException(csar.right().value()); } return csar.left().value(); } - private void auditAndThrowException(Resource resource, User user, AuditingActionEnum auditingAction, ActionStatus status, String... params){ + private void auditAndThrowException(Resource resource, User user, AuditingActionEnum auditingAction, ActionStatus status, String... params) { ResponseFormat errorResponse = componentsUtils.getResponseFormat(status, params); componentsUtils.auditResource(errorResponse, user, resource, auditingAction); throw new ByResponseFormatComponentException(errorResponse, params); } - private Either, ResponseFormat> validateAndParseCsar(Service service, User user, - Map payload, String csarUUID) { + private Either, ResponseFormat> validateAndParseCsar(Service service, User user, Map payload, + String csarUUID) { Map csar = getCsar(service, user, payload, csarUUID); - Either validateCsarStatus = CsarValidationUtils.validateCsar(csar, - csarUUID, componentsUtils); + Either validateCsarStatus = CsarValidationUtils.validateCsar(csar, 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); - + BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED); return Either.right(responseFormat); } - - Either, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils - .getToscaYaml(csar, csarUUID, componentsUtils); - + Either, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar, 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); + BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED); return Either.right(responseFormat); } return toscaYamlCsarStatus; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarInfo.java index feb18c22e6..f5a1409e68 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarInfo.java @@ -21,8 +21,23 @@ */ package org.openecomp.sdc.be.components.csar; +import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; +import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; +import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement; + import com.google.common.annotations.VisibleForTesting; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.Set; +import java.util.regex.Pattern; import lombok.Getter; import lombok.Setter; import org.apache.commons.collections.CollectionUtils; @@ -42,25 +57,10 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; import org.yaml.snakeyaml.Yaml; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.Set; -import java.util.regex.Pattern; - -import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; -import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; -import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement; - public class CsarInfo { - private static final Logger log = Logger.getLogger(CsarInfo.class); + private static final Logger log = Logger.getLogger(CsarInfo.class); + private final NonManoConfiguration nonManoConfiguration; @Getter @Setter private String vfResourceName; @@ -85,10 +85,10 @@ public class CsarInfo { private boolean isUpdate; @Getter private Map createdNodes; - private final NonManoConfiguration nonManoConfiguration; @SuppressWarnings("unchecked") - public CsarInfo(User modifier, String csarUUID, Map csar, String vfResourceName, String mainTemplateName, String mainTemplateContent, boolean isUpdate){ + public CsarInfo(User modifier, String csarUUID, Map csar, String vfResourceName, String mainTemplateName, + String mainTemplateContent, boolean isUpdate) { this.vfResourceName = vfResourceName; this.modifier = modifier; this.csarUUID = csarUUID; @@ -99,7 +99,7 @@ public class CsarInfo { this.createdNodesToscaResourceNames = new HashMap<>(); this.cvfcToCreateQueue = new PriorityQueue<>(); this.isUpdate = isUpdate; - this.createdNodes = new HashMap<>(); + this.createdNodes = new HashMap<>(); this.nonManoConfiguration = NonManoConfigurationManager.getInstance().getNonManoConfiguration(); } @@ -108,14 +108,36 @@ public class CsarInfo { this.nonManoConfiguration = nonManoConfiguration; } + @SuppressWarnings("unchecked") + public static void markNestedVfc(Map mappedToscaTemplate, Map nodeTypesInfo) { + findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP).right() + .on(nts -> processNodeTemplates((Map) nts, nodeTypesInfo)); + } + + @SuppressWarnings("unchecked") + private static ResultStatusEnum processNodeTemplates(Map nodeTemplates, Map nodeTypesInfo) { + nodeTemplates.values().forEach(nt -> processNodeTemplate(nodeTypesInfo, (Map) nt)); + return ResultStatusEnum.OK; + } + + private static void processNodeTemplate(Map nodeTypesInfo, Map nodeTemplate) { + if (nodeTemplate.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) { + String type = (String) nodeTemplate.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()); + if (nodeTypesInfo.containsKey(type)) { + NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type); + if (nodeTypeInfo.isSubstitutionMapping() && type.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { + nodeTypeInfo.setNested(true); + } + } + } + } + public void addNodeToQueue(String nodeName) { - if(!cvfcToCreateQueue.contains(nodeName)) { + if (!cvfcToCreateQueue.contains(nodeName)) { cvfcToCreateQueue.add(nodeName); } else { - log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", nodeName, - getVfResourceName()); - throw new ByActionStatusComponentException(ActionStatus.CFVC_LOOP_DETECTED, - getVfResourceName(), nodeName); + log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", nodeName, getVfResourceName()); + throw new ByActionStatusComponentException(ActionStatus.CFVC_LOOP_DETECTED, getVfResourceName(), nodeName); } } @@ -131,7 +153,7 @@ public class CsarInfo { this.isUpdate = isUpdate; } - public Map extractNodeTypesInfo() { + public Map extractNodeTypesInfo() { Map nodeTypesInfo = new HashMap<>(); List> globalSubstitutes = new ArrayList<>(); final Set nodeTypesUsedInNodeTemplates = new HashSet<>(); @@ -147,17 +169,15 @@ public class CsarInfo { } @SuppressWarnings("unchecked") - private void extractNodeTypeInfo(Map nodeTypesInfo, - List> globalSubstitutes, final Set nodeTypesUsedInNodeTemplates, Map.Entry entry) { + private void extractNodeTypeInfo(Map nodeTypesInfo, List> globalSubstitutes, + final Set nodeTypesUsedInNodeTemplates, Map.Entry entry) { if (isAServiceTemplate(entry.getKey())) { if (isGlobalSubstitute(entry.getKey())) { globalSubstitutes.add(entry); } else { Map mappedToscaTemplate = (Map) new Yaml().load(new String(entry.getValue())); - findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP) - .right() - .on(sub->handleSubstitutionMappings(nodeTypesInfo, entry, mappedToscaTemplate, (Map)sub)); - + findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP).right() + .on(sub -> handleSubstitutionMappings(nodeTypesInfo, entry, mappedToscaTemplate, (Map) sub)); final Either nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP); if (nodeTypesEither.isLeft()) { @@ -167,37 +187,38 @@ public class CsarInfo { } } } - + private boolean isAServiceTemplate(final String filePath) { - return Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(filePath).matches(); + return Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(filePath).matches(); } - + private Set findNodeTypesUsedInNodeTemplates(final Map> nodeTemplates) { - final Set nodeTypes = new HashSet<>(); - for (final Map nodeTemplate : nodeTemplates.values()) { - nodeTypes.add((String)nodeTemplate.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())); - } - return nodeTypes; + final Set nodeTypes = new HashSet<>(); + for (final Map nodeTemplate : nodeTemplates.values()) { + nodeTypes.add((String) nodeTemplate.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())); + } + return nodeTypes; } - private ResultStatusEnum handleSubstitutionMappings(Map nodeTypesInfo, Map.Entry entry, Map mappedToscaTemplate, Map substitutionMappings) { - final Set nodeTypesDefinedInTemplate = findNodeTypesDefinedInTemplate(mappedToscaTemplate); - if (substitutionMappings.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()) && !nodeTypesDefinedInTemplate.contains(substitutionMappings.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()))) { + private ResultStatusEnum handleSubstitutionMappings(Map nodeTypesInfo, Map.Entry entry, + Map mappedToscaTemplate, Map substitutionMappings) { + final Set nodeTypesDefinedInTemplate = findNodeTypesDefinedInTemplate(mappedToscaTemplate); + if (substitutionMappings.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()) && !nodeTypesDefinedInTemplate + .contains(substitutionMappings.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()))) { NodeTypeInfo nodeTypeInfo = new NodeTypeInfo(); nodeTypeInfo.setSubstitutionMapping(true); - nodeTypeInfo.setType( - (String) substitutionMappings.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName())); + nodeTypeInfo.setType((String) substitutionMappings.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName())); nodeTypeInfo.setTemplateFileName(entry.getKey()); nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate); nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo); } return ResultStatusEnum.OK; } - + @SuppressWarnings("unchecked") - private Set findNodeTypesDefinedInTemplate(final Map mappedToscaTemplate) { - final Either nodeTypesEither = findToscaElement(mappedToscaTemplate, - TypeUtils.ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP); + private Set findNodeTypesDefinedInTemplate(final Map mappedToscaTemplate) { + final Either nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES, + ToscaElementTypeEnum.MAP); if (nodeTypesEither.isLeft()) { final Map nodeTypes = (Map) nodeTypesEither.left().value(); return nodeTypes.keySet(); @@ -206,18 +227,17 @@ public class CsarInfo { } private boolean isGlobalSubstitute(String fileName) { - return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) - || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE); + return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName + .equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE); } @SuppressWarnings("unchecked") - private void setDerivedFrom(Map nodeTypesInfo, - List> globalSubstitutes) { + 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 = findToscaElement(mappedToscaTemplate, - TypeUtils.ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP); + Either nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES, + ToscaElementTypeEnum.MAP); if (nodeTypesEither.isLeft()) { Map nodeTypes = (Map) nodeTypesEither.left().value(); for (Map.Entry nodeType : nodeTypes.entrySet()) { @@ -239,24 +259,16 @@ public class CsarInfo { } @SuppressWarnings("unchecked") - public static void markNestedVfc(Map mappedToscaTemplate, Map nodeTypesInfo) { - findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES, - ToscaElementTypeEnum.MAP) - .right() - .on(nts-> processNodeTemplates((Map)nts, nodeTypesInfo)); - } - - @SuppressWarnings("unchecked") - private void addGlobalSubstitutionsToNodeTypes(final List> globalSubstitutes, final Set nodeTypesUsedInNodeTemplates, final Map nodeTypesInfo) { + private void addGlobalSubstitutionsToNodeTypes(final List> globalSubstitutes, + final Set nodeTypesUsedInNodeTemplates, final Map nodeTypesInfo) { for (Map.Entry entry : globalSubstitutes) { final String yamlFileContents = new String(entry.getValue()); final Map mappedToscaTemplate = (Map) new Yaml().load(yamlFileContents); - final Either nodeTypesEither = findToscaElement(mappedToscaTemplate, - TypeUtils.ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP); + final Either nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES, + ToscaElementTypeEnum.MAP); if (nodeTypesEither.isLeft()) { final Map nodeTypes = (Map) nodeTypesEither.left().value(); for (final Map.Entry nodeType : nodeTypes.entrySet()) { - if (!nodeTypesInfo.containsKey(nodeType.getKey()) && nodeTypesUsedInNodeTemplates.contains(nodeType.getKey())) { nodeTypesInfo.put(nodeType.getKey(), buildNodeTypeInfo(nodeType, entry.getKey(), mappedToscaTemplate)); } @@ -266,56 +278,35 @@ public class CsarInfo { } @SuppressWarnings("unchecked") - private static ResultStatusEnum processNodeTemplates( Map nodeTemplates, Map nodeTypesInfo) { - nodeTemplates.values().forEach(nt->processNodeTemplate(nodeTypesInfo, (Map) nt)); - return ResultStatusEnum.OK; - } - - @SuppressWarnings("unchecked") - private NodeTypeInfo buildNodeTypeInfo(final Map.Entry nodeType, final String templateFileName, final Map mappedToscaTemplate ) { + private NodeTypeInfo buildNodeTypeInfo(final Map.Entry nodeType, final String templateFileName, + final Map mappedToscaTemplate) { final NodeTypeInfo nodeTypeInfo = new NodeTypeInfo(); nodeTypeInfo.setSubstitutionMapping(false); nodeTypeInfo.setNested(true); nodeTypeInfo.setType(nodeType.getKey()); nodeTypeInfo.setTemplateFileName(templateFileName); nodeTypeInfo.setMappedToscaTemplate(buildToscaTemplateForNode(nodeType.getKey(), mappedToscaTemplate)); - final Map nodeTypeMap = (Map) nodeType.getValue(); final List derivedFrom = new ArrayList<>(); derivedFrom.add((String) nodeTypeMap.get(TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName())); nodeTypeInfo.setDerivedFrom(derivedFrom); - return nodeTypeInfo; } - + @SuppressWarnings("unchecked") private Map buildToscaTemplateForNode(final String nodeTypeName, final Map mappedToscaTemplate) { final Map mappedToscaTemplateforNode = new HashMap<>(mappedToscaTemplate); - - final Either nodeTypesEither = findToscaElement(mappedToscaTemplate, - TypeUtils.ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP); + final Either nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES, + ToscaElementTypeEnum.MAP); final Map nodeTypes = new HashMap<>(); if (nodeTypesEither.isLeft()) { final Map allNodeTypes = (Map) nodeTypesEither.left().value(); nodeTypes.put(nodeTypeName, allNodeTypes.get(nodeTypeName)); } - mappedToscaTemplateforNode.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), nodeTypes); return mappedToscaTemplateforNode; } - private static void processNodeTemplate(Map nodeTypesInfo, Map nodeTemplate) { - if (nodeTemplate.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) { - String type = (String) nodeTemplate.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()); - if (nodeTypesInfo.containsKey(type)) { - NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type); - if (nodeTypeInfo.isSubstitutionMapping() && type.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { - nodeTypeInfo.setNested(true); - } - } - } - } - /** * Gets the software information yaml path from the csar file map. * @@ -325,10 +316,7 @@ public class CsarInfo { if (MapUtils.isEmpty(csar)) { return Optional.empty(); } - final NonManoFolderType softwareInformationType = - nonManoConfiguration.getNonManoType(NonManoArtifactType.ONAP_SW_INFORMATION); - return csar.keySet().stream() - .filter(filePath -> filePath.startsWith(softwareInformationType.getPath())) - .findFirst(); + final NonManoFolderType softwareInformationType = nonManoConfiguration.getNonManoType(NonManoArtifactType.ONAP_SW_INFORMATION); + return csar.keySet().stream().filter(filePath -> filePath.startsWith(softwareInformationType.getPath())).findFirst(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java index 58f46bcfa7..32e0918ef6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java @@ -21,13 +21,49 @@ */ package org.openecomp.sdc.be.components.csar; +import static java.util.stream.Collectors.toList; +import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; +import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; +import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaListElement; +import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaMapElement; +import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement; +import static org.openecomp.sdc.be.components.impl.ImportUtils.loadYamlAsStrictMap; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ARTIFACTS; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITIES; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITY; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DESCRIPTION; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.FILE; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GET_INPUT; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GROUPS; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.IS_PASSWORD; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.MEMBERS; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.POLICIES; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.PROPERTIES; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.REQUIREMENTS; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TARGETS; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TYPE; +import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES; + import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; import fj.data.Either; +import java.util.ArrayList; +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.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -66,43 +102,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.parser.ParserException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import static java.util.stream.Collectors.toList; -import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; -import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; -import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaListElement; -import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaMapElement; -import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement; -import static org.openecomp.sdc.be.components.impl.ImportUtils.loadYamlAsStrictMap; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ARTIFACTS; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITIES; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITY; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DESCRIPTION; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.FILE; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GET_INPUT; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GROUPS; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.IS_PASSWORD; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.MEMBERS; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.POLICIES; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.PROPERTIES; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.REQUIREMENTS; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TARGETS; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TYPE; -import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES; - /** * A handler class designed to parse the YAML file of the service template for a JAVA object */ @@ -113,8 +112,6 @@ public class YamlTemplateParsingHandler { private static final int SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX = 0; private static final int SUB_MAPPING_CAPABILITY_NAME_IDX = 1; private static final Logger log = Logger.getLogger(YamlTemplateParsingHandler.class); - - private Gson gson = new Gson(); private JanusGraphDao janusGraphDao; private GroupTypeBusinessLogic groupTypeBusinessLogic; @@ -122,7 +119,7 @@ public class YamlTemplateParsingHandler { private PolicyTypeBusinessLogic policyTypeBusinessLogic; public YamlTemplateParsingHandler(JanusGraphDao janusGraphDao, GroupTypeBusinessLogic groupTypeBusinessLogic, - AnnotationBusinessLogic annotationBusinessLogic, PolicyTypeBusinessLogic policyTypeBusinessLogic) { + AnnotationBusinessLogic annotationBusinessLogic, PolicyTypeBusinessLogic policyTypeBusinessLogic) { this.janusGraphDao = janusGraphDao; this.groupTypeBusinessLogic = groupTypeBusinessLogic; this.annotationBusinessLogic = annotationBusinessLogic; @@ -130,25 +127,24 @@ public class YamlTemplateParsingHandler { } public ParsedToscaYamlInfo parseResourceInfoFromYAML(String fileName, String resourceYml, Map createdNodesToscaResourceNames, - Map nodeTypesInfo, String nodeName, org.openecomp.sdc.be.model.Component component) { + Map nodeTypesInfo, String nodeName, + org.openecomp.sdc.be.model.Component component) { log.debug("#parseResourceInfoFromYAML - Going to parse yaml {} ", fileName); Map mappedToscaTemplate = getMappedToscaTemplate(fileName, resourceYml, nodeTypesInfo, nodeName); ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo(); - findToscaElement(mappedToscaTemplate, TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL) - .left() - .on(err -> failIfNotTopologyTemplate(fileName)); - + findToscaElement(mappedToscaTemplate, TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL).left().on(err -> failIfNotTopologyTemplate(fileName)); parsedToscaYamlInfo.setInputs(getInputs(mappedToscaTemplate)); parsedToscaYamlInfo.setInstances(getInstances(fileName, mappedToscaTemplate, createdNodesToscaResourceNames)); parsedToscaYamlInfo.setGroups(getGroups(fileName, mappedToscaTemplate)); - if(component instanceof Resource){ + if (component instanceof Resource) { parsedToscaYamlInfo.setPolicies(getPolicies(fileName, mappedToscaTemplate)); } log.debug("#parseResourceInfoFromYAML - The yaml {} has been parsed ", fileName); return parsedToscaYamlInfo; } - private Map getMappedToscaTemplate(String fileName, String resourceYml, Map nodeTypesInfo, String nodeName) { + private Map getMappedToscaTemplate(String fileName, String resourceYml, Map nodeTypesInfo, + String nodeName) { Map mappedToscaTemplate; if (isNodeExist(nodeTypesInfo, nodeName)) { mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); @@ -174,25 +170,16 @@ public class YamlTemplateParsingHandler { } private Map getInputs(Map toscaJson) { - Map inputs = ImportUtils.getInputs(toscaJson, annotationBusinessLogic.getAnnotationTypeOperations()) - .left() - .on(err -> new HashMap<>()); + Map inputs = ImportUtils.getInputs(toscaJson, annotationBusinessLogic.getAnnotationTypeOperations()).left() + .on(err -> new HashMap<>()); annotationBusinessLogic.validateAndMergeAnnotationsAndAssignToInput(inputs); return inputs; } private Map getPolicies(String fileName, Map toscaJson) { - - Map foundPolicies = findFirstToscaMapElement(toscaJson, POLICIES) - .left() - .on(err -> logPoliciesNotFound(fileName)); - + Map foundPolicies = findFirstToscaMapElement(toscaJson, POLICIES).left().on(err -> logPoliciesNotFound(fileName)); if (MapUtils.isNotEmpty(foundPolicies)) { - return foundPolicies - .entrySet() - .stream() - .map(this::createPolicy) - .collect(Collectors.toMap(PolicyDefinition::getName, p -> p)); + return foundPolicies.entrySet().stream().map(this::createPolicy).collect(Collectors.toMap(PolicyDefinition::getName, p -> p)); } return Collections.emptyMap(); } @@ -222,7 +209,7 @@ public class YamlTemplateParsingHandler { private void validateAndFillPolicy(PolicyDefinition emptyPolicyDefinition, Map policyTemplateJsonMap) { String policyTypeName = (String) policyTemplateJsonMap.get(TYPE.getElementName()); - if(StringUtils.isEmpty(policyTypeName)){ + if (StringUtils.isEmpty(policyTypeName)) { log.debug("#validateAndFillPolicy - The 'type' member is not found under policy {}", emptyPolicyDefinition.getName()); rollbackWithException(ActionStatus.POLICY_MISSING_POLICY_TYPE, emptyPolicyDefinition.getName()); } @@ -244,23 +231,18 @@ public class YamlTemplateParsingHandler { } private List validateFillPolicyProperties(PolicyTypeDefinition policyTypeDefinition, - Map policyTemplateJsonMap) { + Map policyTemplateJsonMap) { if (MapUtils.isEmpty(policyTemplateJsonMap) || Objects.isNull(policyTypeDefinition)) { return Collections.emptyList(); } List propertyDataDefinitionList = new ArrayList<>(); - Map propertiesMap = - (Map) policyTemplateJsonMap.get(PROPERTIES.getElementName()); + Map propertiesMap = (Map) policyTemplateJsonMap.get(PROPERTIES.getElementName()); if (MapUtils.isEmpty(propertiesMap)) { return Collections.emptyList(); } if (CollectionUtils.isNotEmpty(policyTypeDefinition.getProperties())) { - propertyDataDefinitionList = policyTypeDefinition - .getProperties() - .stream() - .map(propertyDefinition -> setPropertyValue(propertiesMap, - propertyDefinition)) - .collect(Collectors.toList()); + propertyDataDefinitionList = policyTypeDefinition.getProperties().stream() + .map(propertyDefinition -> setPropertyValue(propertiesMap, propertyDefinition)).collect(Collectors.toList()); } return propertyDataDefinitionList; } @@ -277,30 +259,26 @@ public class YamlTemplateParsingHandler { private Map> validateFillPolicyTargets(Map policyTemplateJson) { Map> targets = new EnumMap<>(PolicyTargetType.class); - if (policyTemplateJson.containsKey(TARGETS.getElementName()) - && policyTemplateJson.get(TARGETS.getElementName()) instanceof List ) { + if (policyTemplateJson.containsKey(TARGETS.getElementName()) && policyTemplateJson.get(TARGETS.getElementName()) instanceof List) { List targetsElement = (List) policyTemplateJson.get(TARGETS.getElementName()); targets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsElement); } return targets; } - private Map getInstances(String yamlName, Map toscaJson, Map createdNodesToscaResourceNames) { - - Map nodeTemlates = findFirstToscaMapElement(toscaJson, NODE_TEMPLATES) - .left() - .on(err -> failIfNoNodeTemplates(yamlName)); - + private Map getInstances(String yamlName, Map toscaJson, + Map createdNodesToscaResourceNames) { + Map nodeTemlates = findFirstToscaMapElement(toscaJson, NODE_TEMPLATES).left().on(err -> failIfNoNodeTemplates(yamlName)); return getInstances(toscaJson, createdNodesToscaResourceNames, nodeTemlates); } - private Map getInstances(Map toscaJson, Map createdNodesToscaResourceNames, Map nodeTemlates) { + private Map getInstances(Map toscaJson, Map createdNodesToscaResourceNames, + Map nodeTemlates) { Map moduleComponentInstances; Map substitutionMappings = getSubstitutionMappings(toscaJson); - moduleComponentInstances = nodeTemlates.entrySet() - .stream() - .map(node -> buildModuleComponentInstanceInfo(node, substitutionMappings, createdNodesToscaResourceNames)) - .collect(Collectors.toMap(UploadComponentInstanceInfo::getName, i -> i)); + moduleComponentInstances = nodeTemlates.entrySet().stream() + .map(node -> buildModuleComponentInstanceInfo(node, substitutionMappings, createdNodesToscaResourceNames)) + .collect(Collectors.toMap(UploadComponentInstanceInfo::getName, i -> i)); return moduleComponentInstances; } @@ -315,29 +293,22 @@ public class YamlTemplateParsingHandler { @SuppressWarnings("unchecked") private Map getGroups(String fileName, Map toscaJson) { - - Map foundGroups = findFirstToscaMapElement(toscaJson, GROUPS) - .left() - .on(err -> logGroupsNotFound(fileName)); - + Map foundGroups = findFirstToscaMapElement(toscaJson, GROUPS).left().on(err -> logGroupsNotFound(fileName)); if (MapUtils.isNotEmpty(foundGroups) && matcheKey(foundGroups)) { - Map groups = foundGroups - .entrySet() - .stream() - .map(this::createGroup) - .collect(Collectors.toMap(GroupDefinition::getName, g -> g)); + Map groups = foundGroups.entrySet().stream().map(this::createGroup) + .collect(Collectors.toMap(GroupDefinition::getName, g -> g)); Map substitutionMappings = getSubstitutionMappings(toscaJson); if (capabilitiesSubstitutionMappingsExist(substitutionMappings)) { - groups.entrySet().forEach(entry -> updateCapabilitiesNames(entry.getValue(), getNamesToUpdate(entry.getKey(), - (Map>) substitutionMappings.get(CAPABILITIES.getElementName())))); + groups.entrySet().forEach(entry -> updateCapabilitiesNames(entry.getValue(), + getNamesToUpdate(entry.getKey(), (Map>) substitutionMappings.get(CAPABILITIES.getElementName())))); } return groups; } return new HashMap<>(); } - private boolean matcheKey(Map foundGroups){ - if (foundGroups!=null && !foundGroups.isEmpty()) { + private boolean matcheKey(Map foundGroups) { + if (foundGroups != null && !foundGroups.isEmpty()) { for (Map.Entry stringObjectEntry : foundGroups.entrySet()) { String key = stringObjectEntry.getKey(); if (key.contains("group")) { @@ -357,18 +328,14 @@ public class YamlTemplateParsingHandler { private void updateCapabilitiesNames(GroupDefinition group, Map capabilityNames) { if (MapUtils.isNotEmpty(group.getCapabilities())) { - group.getCapabilities().values() - .stream() - .flatMap(Collection::stream) - .filter(cap -> capabilityNames.containsKey(cap.getName())) - .forEach(cap -> cap.setName(capabilityNames.get(cap.getName()))); + group.getCapabilities().values().stream().flatMap(Collection::stream).filter(cap -> capabilityNames.containsKey(cap.getName())) + .forEach(cap -> cap.setName(capabilityNames.get(cap.getName()))); } } private Map getNamesToUpdate(String name, Map> pair) { - return pair.entrySet().stream() - .filter(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX).equalsIgnoreCase(name)) - .collect(Collectors.toMap(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_NAME_IDX), Map.Entry::getKey, (n1 ,n2) -> n1)); + return pair.entrySet().stream().filter(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX).equalsIgnoreCase(name)) + .collect(Collectors.toMap(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_NAME_IDX), Map.Entry::getKey, (n1, n2) -> n1)); } private boolean capabilitiesSubstitutionMappingsExist(Map substitutionMappings) { @@ -420,30 +387,28 @@ public class YamlTemplateParsingHandler { } private void setMembersFromList(GroupDefinition groupInfo, List membersAsList) { - groupInfo.setMembers(membersAsList - .stream() - .collect(Collectors.toMap(Object::toString, member -> ""))); + groupInfo.setMembers(membersAsList.stream().collect(Collectors.toMap(Object::toString, member -> ""))); } @SuppressWarnings("unchecked") private void validateUpdateGroupProperties(GroupDefinition groupInfo, Map groupTemplateJsonMap) { if (groupTemplateJsonMap.containsKey(PROPERTIES.getElementName())) { Object propertiesElement = groupTemplateJsonMap.get(PROPERTIES.getElementName()); - if (propertiesElement instanceof Map){ + if (propertiesElement instanceof Map) { mergeGroupProperties(groupInfo, (Map) propertiesElement); } } } private void mergeGroupProperties(GroupDefinition groupInfo, Map parsedProperties) { - if(CollectionUtils.isNotEmpty(groupInfo.getProperties())){ + if (CollectionUtils.isNotEmpty(groupInfo.getProperties())) { validateGroupProperties(parsedProperties, groupInfo); groupInfo.getProperties().forEach(p -> mergeGroupProperty(p, parsedProperties)); } } private void mergeGroupProperty(PropertyDataDefinition property, Map parsedProperties) { - if(parsedProperties.containsKey(property.getName())){ + if (parsedProperties.containsKey(property.getName())) { Object propValue = parsedProperties.get(property.getName()); if (valueNotContainsPattern(propertyValuePattern, propValue)) { setPropertyValueAndGetInputsValues(property, propValue); @@ -452,7 +417,7 @@ public class YamlTemplateParsingHandler { } private void setPropertyValueAndGetInputsValues(PropertyDataDefinition property, Object propValue) { - if(propValue != null){ + if (propValue != null) { UploadPropInfo uploadPropInfo = buildProperty(property.getName(), propValue); property.setValue(convertPropertyValue(ToscaPropertyType.isValidType(property.getType()), uploadPropInfo.getValue())); property.setGetInputValues(uploadPropInfo.getGet_input()); @@ -473,19 +438,18 @@ public class YamlTemplateParsingHandler { private void setDescription(GroupDefinition groupInfo, Map groupTemplateJsonMap) { if (groupTemplateJsonMap.containsKey(DESCRIPTION.getElementName())) { - groupInfo.setDescription( - (String) groupTemplateJsonMap.get(DESCRIPTION.getElementName())); + groupInfo.setDescription((String) groupTemplateJsonMap.get(DESCRIPTION.getElementName())); } } private void validateAndFillGroup(GroupDefinition groupInfo, Map groupTemplateJsonMap) { String type = (String) groupTemplateJsonMap.get(TYPE.getElementName()); - if(StringUtils.isEmpty(type)){ + if (StringUtils.isEmpty(type)) { log.debug("#validateAndFillGroup - The 'type' member is not found under group {}", groupInfo.getName()); rollbackWithException(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupInfo.getName()); } groupInfo.setType(type); - GroupTypeDefinition groupType = groupTypeBusinessLogic.getLatestGroupTypeByType(type); + GroupTypeDefinition groupType = groupTypeBusinessLogic.getLatestGroupTypeByType(type); if (groupType == null) { log.debug("#validateAndFillGroup - The group type {} not found", groupInfo.getName()); rollbackWithException(ActionStatus.GROUP_TYPE_IS_INVALID, type); @@ -498,17 +462,14 @@ public class YamlTemplateParsingHandler { @SuppressWarnings("unchecked") private void validateUpdateGroupCapabilities(GroupDefinition groupInfo, Map groupTemplateJsonMap) { - if (groupTemplateJsonMap.containsKey(CAPABILITIES.getElementName())) { Object capabilities = groupTemplateJsonMap.get(CAPABILITIES.getElementName()); if (capabilities instanceof List) { - validateUpdateCapabilities(groupInfo, ((List) capabilities).stream() - .map(o -> buildGroupCapability(groupInfo, o)) - .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities))); + validateUpdateCapabilities(groupInfo, ((List) capabilities).stream().map(o -> buildGroupCapability(groupInfo, o)) + .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities))); } else if (capabilities instanceof Map) { - validateUpdateCapabilities(groupInfo, ((Map) capabilities).entrySet() - .stream() - .map(e -> buildGroupCapability(groupInfo, e)) + validateUpdateCapabilities(groupInfo, + ((Map) capabilities).entrySet().stream().map(e -> buildGroupCapability(groupInfo, e)) .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities))); } else { log.debug("#setCapabilities - Failed to import the capabilities of the group {}. ", groupInfo.getName()); @@ -527,7 +488,8 @@ public class YamlTemplateParsingHandler { if (MapUtils.isEmpty(group.getCapabilities())) { failOnMissingCapabilityTypes(group, Lists.newArrayList(parsedCapabilities.keySet())); } - List missingCapTypes = parsedCapabilities.keySet().stream().filter(ct -> !group.getCapabilities().containsKey(ct)).collect(toList()); + List missingCapTypes = parsedCapabilities.keySet().stream().filter(ct -> !group.getCapabilities().containsKey(ct)) + .collect(toList()); if (CollectionUtils.isNotEmpty(missingCapTypes)) { failOnMissingCapabilityTypes(group, missingCapTypes); } @@ -535,7 +497,8 @@ public class YamlTemplateParsingHandler { } } - private void validateCapabilities(GroupDefinition group, List capabilities, Map parsedCapabilities) { + private void validateCapabilities(GroupDefinition group, List capabilities, + Map parsedCapabilities) { List allowedCapNames = capabilities.stream().map(CapabilityDefinition::getName).distinct().collect(toList()); List missingCapNames = parsedCapabilities.keySet().stream().filter(c -> !allowedCapNames.contains(c)).collect(toList()); if (CollectionUtils.isNotEmpty(missingCapNames)) { @@ -549,33 +512,30 @@ public class YamlTemplateParsingHandler { } private void validateCapabilityProperties(CapabilityDefinition capability, CapabilityDefinition parsedCapability) { - if(parsedCapability != null && parsedCapability.getProperties() != null){ - List parsedPropertiesNames = parsedCapability.getProperties() - .stream() - .map(ComponentInstanceProperty::getName).collect(toList()); - validateProperties(capability.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames, ActionStatus.PROPERTY_NOT_FOUND, capability.getName(), capability.getType()); + if (parsedCapability != null && parsedCapability.getProperties() != null) { + List parsedPropertiesNames = parsedCapability.getProperties().stream().map(ComponentInstanceProperty::getName).collect(toList()); + validateProperties(capability.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames, + ActionStatus.PROPERTY_NOT_FOUND, capability.getName(), capability.getType()); } } - private void validateGroupProperties(Map parsedProperties, GroupDefinition groupInfo) { - List parsedPropertiesNames = parsedProperties.entrySet() - .stream() - .map(Map.Entry::getKey).collect(toList()); - validateProperties(groupInfo.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames, ActionStatus.GROUP_PROPERTY_NOT_FOUND, groupInfo.getName(), groupInfo.getType()); + private void validateGroupProperties(Map parsedProperties, GroupDefinition groupInfo) { + List parsedPropertiesNames = parsedProperties.entrySet().stream().map(Map.Entry::getKey).collect(toList()); + validateProperties(groupInfo.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames, + ActionStatus.GROUP_PROPERTY_NOT_FOUND, groupInfo.getName(), groupInfo.getType()); } - private void validateProperties(List validProperties, List parsedProperties, ActionStatus actionStatus, String name, String type) { + private void validateProperties(List validProperties, List parsedProperties, ActionStatus actionStatus, String name, + String type) { if (CollectionUtils.isNotEmpty(parsedProperties)) { - verifyMissingProperties(actionStatus, name, type, parsedProperties - .stream() - .filter(n -> !validProperties.contains(n)) - .collect(toList())); + verifyMissingProperties(actionStatus, name, type, parsedProperties.stream().filter(n -> !validProperties.contains(n)).collect(toList())); } } private void verifyMissingProperties(ActionStatus actionStatus, String name, String type, List missingProperties) { if (CollectionUtils.isNotEmpty(missingProperties)) { - log.debug("#validateProperties - Failed to validate properties. The properties {} are missing on {} of the type {}. ", missingProperties.toString(), name, type); + log.debug("#validateProperties - Failed to validate properties. The properties {} are missing on {} of the type {}. ", + missingProperties.toString(), name, type); rollbackWithException(actionStatus, missingProperties.toString(), missingProperties.toString(), name, type); } } @@ -624,10 +584,9 @@ public class YamlTemplateParsingHandler { } @SuppressWarnings("unchecked") - private UploadComponentInstanceInfo buildModuleComponentInstanceInfo( - Map.Entry nodeTemplateJsonEntry, Map substitutionMappings, - Map createdNodesToscaResourceNames) { - + private UploadComponentInstanceInfo buildModuleComponentInstanceInfo(Map.Entry nodeTemplateJsonEntry, + Map substitutionMappings, + Map createdNodesToscaResourceNames) { UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo(); nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey()); try { @@ -659,13 +618,12 @@ public class YamlTemplateParsingHandler { private void setSubstitutions(Map substitutionMappings, UploadComponentInstanceInfo nodeTemplateInfo) { if (substitutionMappings != null) { if (substitutionMappings.containsKey(CAPABILITIES.getElementName())) { - nodeTemplateInfo.setCapabilitiesNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(), (Map>) substitutionMappings - .get(CAPABILITIES.getElementName()))); + nodeTemplateInfo.setCapabilitiesNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(), + (Map>) substitutionMappings.get(CAPABILITIES.getElementName()))); } if (substitutionMappings.containsKey(REQUIREMENTS.getElementName())) { - nodeTemplateInfo.setRequirementsNamesToUpdate(getNamesToUpdate( - nodeTemplateInfo.getName(), (Map>) substitutionMappings - .get(REQUIREMENTS.getElementName()))); + nodeTemplateInfo.setRequirementsNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(), + (Map>) substitutionMappings.get(REQUIREMENTS.getElementName()))); } } } @@ -706,8 +664,8 @@ public class YamlTemplateParsingHandler { } } - private void setToscaResourceType(Map createdNodesToscaResourceNames, - UploadComponentInstanceInfo nodeTemplateInfo, Map nodeTemplateJsonMap) { + private void setToscaResourceType(Map createdNodesToscaResourceNames, UploadComponentInstanceInfo nodeTemplateInfo, + Map nodeTemplateJsonMap) { if (nodeTemplateJsonMap.containsKey(TYPE.getElementName())) { String toscaResourceType = (String) nodeTemplateJsonMap.get(TYPE.getElementName()); if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) { @@ -717,28 +675,22 @@ public class YamlTemplateParsingHandler { } } - private void setDirectives(UploadComponentInstanceInfo nodeTemplateInfo, - Map nodeTemplateJsonMap) { - List directives = - (List) nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.DIRECTIVES.getElementName()); + private void setDirectives(UploadComponentInstanceInfo nodeTemplateInfo, Map nodeTemplateJsonMap) { + List directives = (List) nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.DIRECTIVES.getElementName()); nodeTemplateInfo.setDirectives(directives); } - private void setNodeFilter(UploadComponentInstanceInfo nodeTemplateInfo, - Map nodeTemplateJsonMap) { + private void setNodeFilter(UploadComponentInstanceInfo nodeTemplateInfo, Map nodeTemplateJsonMap) { if (nodeTemplateJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName())) { - nodeTemplateInfo.setUploadNodeFilterInfo( - new NodeFilterUploadCreator().createNodeFilterData(nodeTemplateJsonMap.get( - TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName()))); + nodeTemplateInfo.setUploadNodeFilterInfo(new NodeFilterUploadCreator() + .createNodeFilterData(nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName()))); } } @SuppressWarnings("unchecked") private Map> createReqModuleFromYaml(Map nodeTemplateJsonMap) { Map> moduleRequirements = new HashMap<>(); - Either, ResultStatusEnum> requirementsListRes = - findFirstToscaListElement(nodeTemplateJsonMap, REQUIREMENTS); - + Either, ResultStatusEnum> requirementsListRes = findFirstToscaListElement(nodeTemplateJsonMap, REQUIREMENTS); if (requirementsListRes.isLeft()) { for (Object jsonReqObj : requirementsListRes.left().value()) { String reqName = ((Map) jsonReqObj).keySet().iterator().next(); @@ -746,8 +698,7 @@ public class YamlTemplateParsingHandler { addModuleNodeTemplateReq(moduleRequirements, reqJson, reqName); } } else { - Either, ResultStatusEnum> requirementsMapRes = - findFirstToscaMapElement(nodeTemplateJsonMap, REQUIREMENTS); + Either, ResultStatusEnum> requirementsMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, REQUIREMENTS); if (requirementsMapRes.isLeft()) { for (Map.Entry entry : requirementsMapRes.left().value().entrySet()) { String reqName = entry.getKey(); @@ -760,7 +711,6 @@ public class YamlTemplateParsingHandler { } private void addModuleNodeTemplateReq(Map> moduleRequirements, Object requirementJson, String requirementName) { - UploadReqInfo requirement = buildModuleNodeTemplateReg(requirementJson); requirement.setName(requirementName); if (moduleRequirements.containsKey(requirementName)) { @@ -775,8 +725,7 @@ public class YamlTemplateParsingHandler { @SuppressWarnings("unchecked") private Map> createArtifactsModuleFromYaml(Map nodeTemplateJsonMap) { Map> moduleArtifacts = new HashMap<>(); - Either, ResultStatusEnum> ArtifactsListRes = - findFirstToscaListElement(nodeTemplateJsonMap, ARTIFACTS); + Either, ResultStatusEnum> ArtifactsListRes = findFirstToscaListElement(nodeTemplateJsonMap, ARTIFACTS); if (ArtifactsListRes.isLeft()) { for (Object jsonArtifactObj : ArtifactsListRes.left().value()) { String key = ((Map) jsonArtifactObj).keySet().iterator().next(); @@ -784,8 +733,7 @@ public class YamlTemplateParsingHandler { addModuleNodeTemplateArtifacts(moduleArtifacts, artifactJson, key); } } else { - Either>, ResultStatusEnum> ArtifactsMapRes = - findFirstToscaMapElement(nodeTemplateJsonMap, ARTIFACTS); + Either>, ResultStatusEnum> ArtifactsMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, ARTIFACTS); if (ArtifactsMapRes.isLeft()) { for (Map.Entry> entry : ArtifactsMapRes.left().value().entrySet()) { String artifactName = entry.getKey(); @@ -797,8 +745,8 @@ public class YamlTemplateParsingHandler { return moduleArtifacts; } - private void addModuleNodeTemplateArtifacts(Map> moduleArtifacts, Object artifactJson, String artifactName) { - + private void addModuleNodeTemplateArtifacts(Map> moduleArtifacts, Object artifactJson, + String artifactName) { UploadArtifactInfo artifact = buildModuleNodeTemplateArtifact(artifactJson); artifact.setName(artifactName); if (moduleArtifacts.containsKey(ARTIFACTS.getElementName())) { @@ -828,12 +776,10 @@ public class YamlTemplateParsingHandler { } } - @SuppressWarnings("unchecked") private Map> createCapModuleFromYaml(Map nodeTemplateJsonMap) { Map> moduleCap = new HashMap<>(); - Either, ResultStatusEnum> capabilitiesListRes = - findFirstToscaListElement(nodeTemplateJsonMap, CAPABILITIES); + Either, ResultStatusEnum> capabilitiesListRes = findFirstToscaListElement(nodeTemplateJsonMap, CAPABILITIES); if (capabilitiesListRes.isLeft()) { for (Object jsonCapObj : capabilitiesListRes.left().value()) { String key = ((Map) jsonCapObj).keySet().iterator().next(); @@ -841,8 +787,7 @@ public class YamlTemplateParsingHandler { addModuleNodeTemplateCap(moduleCap, capJson, key); } } else { - Either, ResultStatusEnum> capabilitiesMapRes = - findFirstToscaMapElement(nodeTemplateJsonMap, CAPABILITIES); + Either, ResultStatusEnum> capabilitiesMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, CAPABILITIES); if (capabilitiesMapRes.isLeft()) { for (Map.Entry entry : capabilitiesMapRes.left().value().entrySet()) { String capName = entry.getKey(); @@ -855,7 +800,6 @@ public class YamlTemplateParsingHandler { } private void addModuleNodeTemplateCap(Map> moduleCap, Object capJson, String key) { - UploadCapInfo capabilityDef = buildModuleNodeTemplateCap(capJson); capabilityDef.setKey(key); if (moduleCap.containsKey(key)) { @@ -870,7 +814,6 @@ public class YamlTemplateParsingHandler { @SuppressWarnings("unchecked") private UploadCapInfo buildModuleNodeTemplateCap(Object capObject) { UploadCapInfo capTemplateInfo = new UploadCapInfo(); - if (capObject instanceof String) { String nodeTemplateJsonString = (String) capObject; capTemplateInfo.setNode(nodeTemplateJsonString); @@ -888,11 +831,9 @@ public class YamlTemplateParsingHandler { capTemplateInfo.setType((String) nodeTemplateJsonMap.get(TYPE.getElementName())); } if (nodeTemplateJsonMap.containsKey(VALID_SOURCE_TYPES.getElementName())) { - Either, ResultStatusEnum> validSourceTypesRes = - findFirstToscaListElement(nodeTemplateJsonMap, VALID_SOURCE_TYPES); + Either, ResultStatusEnum> validSourceTypesRes = findFirstToscaListElement(nodeTemplateJsonMap, VALID_SOURCE_TYPES); if (validSourceTypesRes.isLeft()) { - capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream() - .map(Object::toString).collect(toList())); + capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(Object::toString).collect(toList())); } } if (nodeTemplateJsonMap.containsKey(PROPERTIES.getElementName())) { @@ -906,7 +847,6 @@ public class YamlTemplateParsingHandler { @SuppressWarnings("unchecked") private UploadReqInfo buildModuleNodeTemplateReg(Object regObject) { - UploadReqInfo regTemplateInfo = new UploadReqInfo(); if (regObject instanceof String) { String nodeTemplateJsonString = (String) regObject; @@ -917,18 +857,15 @@ public class YamlTemplateParsingHandler { regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(NODE.getElementName())); } if (nodeTemplateJsonMap.containsKey(CAPABILITY.getElementName())) { - regTemplateInfo.setCapabilityName( - (String) nodeTemplateJsonMap.get(CAPABILITY.getElementName())); + regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(CAPABILITY.getElementName())); } } return regTemplateInfo; } private Map> buildPropModuleFromYaml(Map nodeTemplateJsonMap) { - Map> moduleProp = new HashMap<>(); - Either, ResultStatusEnum> toscaProperties = - findFirstToscaMapElement(nodeTemplateJsonMap, PROPERTIES); + Either, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(nodeTemplateJsonMap, PROPERTIES); if (toscaProperties.isLeft()) { Map jsonProperties = toscaProperties.left().value(); for (Map.Entry jsonPropObj : jsonProperties.entrySet()) { @@ -953,54 +890,43 @@ public class YamlTemplateParsingHandler { @SuppressWarnings("unchecked") private UploadPropInfo buildProperty(String propName, Object propValue) { - UploadPropInfo propertyDef = new UploadPropInfo(); propertyDef.setValue(propValue); propertyDef.setName(propName); if (propValue instanceof Map) { if (((Map) propValue).containsKey(TYPE.getElementName())) { - propertyDef.setType(((Map) propValue) - .get(TYPE.getElementName()).toString()); + propertyDef.setType(((Map) propValue).get(TYPE.getElementName()).toString()); } if (containsGetInput(propValue)) { fillInputRecursively(propName, (Map) propValue, propertyDef); } - if (((Map) propValue).containsKey(DESCRIPTION.getElementName())) { - propertyDef.setDescription(((Map) propValue) - .get(DESCRIPTION.getElementName()).toString()); + propertyDef.setDescription(((Map) propValue).get(DESCRIPTION.getElementName()).toString()); } - if (((Map) propValue) - .containsKey(DEFAULT_VALUE.getElementName())) { - propertyDef.setValue(((Map) propValue) - .get(DEFAULT_VALUE.getElementName())); + if (((Map) propValue).containsKey(DEFAULT_VALUE.getElementName())) { + propertyDef.setValue(((Map) propValue).get(DEFAULT_VALUE.getElementName())); } if (((Map) propValue).containsKey(IS_PASSWORD.getElementName())) { - propertyDef.setPassword(Boolean.getBoolean(((Map) propValue) - .get(IS_PASSWORD.getElementName()).toString())); + propertyDef.setPassword(Boolean.getBoolean(((Map) propValue).get(IS_PASSWORD.getElementName()).toString())); } else { propertyDef.setValue(propValue); } } else if (propValue instanceof List) { List propValueList = (List) propValue; - fillInputsListRecursively(propertyDef, propValueList); propertyDef.setValue(propValue); } - return propertyDef; } @SuppressWarnings("unchecked") private boolean containsGetInput(Object propValue) { - return ((Map) propValue).containsKey(GET_INPUT.getElementName()) - || ImportUtils.containsGetInput(propValue); + return ((Map) propValue).containsKey(GET_INPUT.getElementName()) || ImportUtils.containsGetInput(propValue); } @SuppressWarnings("unchecked") private void fillInputsListRecursively(UploadPropInfo propertyDef, List propValueList) { for (Object objValue : propValueList) { - if (objValue instanceof Map) { Map objMap = (Map) objValue; if (objMap.containsKey(GET_INPUT.getElementName())) { @@ -1017,8 +943,7 @@ public class YamlTemplateParsingHandler { } @SuppressWarnings("unchecked") - private void findAndFillInputsListRecursively(UploadPropInfo propertyDef, Map objMap, - Set keys) { + private void findAndFillInputsListRecursively(UploadPropInfo propertyDef, Map objMap, Set keys) { for (String key : keys) { Object value = objMap.get(key); if (value instanceof Map) { @@ -1031,7 +956,6 @@ public class YamlTemplateParsingHandler { } private void fillInputRecursively(String propName, Map propValue, UploadPropInfo propertyDef) { - if (propValue.containsKey(GET_INPUT.getElementName())) { Object getInput = propValue.get(GET_INPUT.getElementName()); GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition(); @@ -1040,10 +964,8 @@ public class YamlTemplateParsingHandler { getInputs = new ArrayList<>(); } if (getInput instanceof String) { - getInputInfo.setInputName((String) getInput); getInputInfo.setPropName(propName); - } else if (getInput instanceof List) { fillInput(propName, getInput, getInputInfo); } @@ -1061,7 +983,6 @@ public class YamlTemplateParsingHandler { Object value = propValue.get(propName); if (value instanceof Map) { fillInputRecursively(propName, (Map) value, propertyDef); - } else if (value instanceof List) { fillInputsRecursively(propertyDef, propName, (List) value); } @@ -1069,9 +990,7 @@ public class YamlTemplateParsingHandler { } private void fillInputsRecursively(UploadPropInfo propertyDef, String propName, List inputs) { - inputs.stream() - .filter(o -> o instanceof Map) - .forEach(o -> fillInputRecursively(propName, (Map)o, propertyDef)); + inputs.stream().filter(o -> o instanceof Map).forEach(o -> fillInputRecursively(propName, (Map) o, propertyDef)); } @SuppressWarnings("unchecked") @@ -1086,10 +1005,8 @@ public class YamlTemplateParsingHandler { } else if (indexObj instanceof Float) { int index = ((Float) indexObj).intValue(); getInputInfo.setIndexValue(index); - } else if (indexObj instanceof Map && ((Map) indexObj) - .containsKey(GET_INPUT.getElementName())) { - Object index = ((Map) indexObj) - .get(GET_INPUT.getElementName()); + } else if (indexObj instanceof Map && ((Map) indexObj).containsKey(GET_INPUT.getElementName())) { + Object index = ((Map) indexObj).get(GET_INPUT.getElementName()); GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition(); getInputInfoIndex.setInputName((String) index); getInputInfoIndex.setPropName(propName); @@ -1119,15 +1036,19 @@ public class YamlTemplateParsingHandler { } private void failOnMissingCapabilityTypes(GroupDefinition groupDefinition, List missingCapTypes) { - log.debug("#failOnMissingCapabilityTypes - Failed to validate the capabilities of the group {}. The capability types {} are missing on the group type {}. ", groupDefinition.getName(), missingCapTypes.toString(), groupDefinition.getType()); - if(CollectionUtils.isNotEmpty(missingCapTypes)) { + log.debug( + "#failOnMissingCapabilityTypes - Failed to validate the capabilities of the group {}. The capability types {} are missing on the group type {}. ", + groupDefinition.getName(), missingCapTypes.toString(), groupDefinition.getType()); + if (CollectionUtils.isNotEmpty(missingCapTypes)) { rollbackWithException(ActionStatus.MISSING_CAPABILITY_TYPE, missingCapTypes.toString()); } } private void failOnMissingCapabilityNames(GroupDefinition groupDefinition, List missingCapNames) { - log.debug("#failOnMissingCapabilityNames - Failed to validate the capabilities of the group {}. The capabilities with the names {} are missing on the group type {}. ", groupDefinition.getName(), missingCapNames.toString(), groupDefinition.getType()); - rollbackWithException(ActionStatus.MISSING_CAPABILITIES, missingCapNames.toString(), CapabilityDataDefinition.OwnerType.GROUP.getValue(), groupDefinition.getName()); + log.debug( + "#failOnMissingCapabilityNames - Failed to validate the capabilities of the group {}. The capabilities with the names {} are missing on the group type {}. ", + groupDefinition.getName(), missingCapNames.toString(), groupDefinition.getType()); + rollbackWithException(ActionStatus.MISSING_CAPABILITIES, missingCapNames.toString(), CapabilityDataDefinition.OwnerType.GROUP.getValue(), + groupDefinition.getName()); } - } 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 index 52179b49f5..a69edfbb4d 100644 --- 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 @@ -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. @@ -17,9 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.util.Properties; +import java.util.UUID; +import javax.annotation.PostConstruct; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import org.apache.http.conn.ConnectTimeoutException; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.common.api.Constants; @@ -33,74 +39,53 @@ import org.openecomp.sdc.common.http.config.ExternalServiceConfig; import org.openecomp.sdc.common.log.wrappers.Logger; 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 = Logger.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"; + private static final Logger logger = Logger.getLogger(AaiRequestHandler.class); + private ExternalServiceConfig aaiConfig; @PostConstruct public void init() { logger.debug("AaiRequestHandler has been initialized."); - aaiConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getAaiConfig(); aaiConfig.getHttpClientConfig().setEnableMetricLogging(true); 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); - + 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 98a8550b7a..410626390c 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 @@ -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. @@ -17,9 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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.stream.Collectors; import lombok.Getter; import lombok.Setter; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; @@ -27,12 +31,6 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Service; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - @Getter @Setter public class ArtifactInfoImpl implements IArtifactInfo { @@ -63,7 +61,8 @@ public class ArtifactInfoImpl implements IArtifactInfo { this.generatedFromUUID = generatedFromUUID; } - public static List convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance, Collection list) { + 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) { @@ -73,14 +72,15 @@ public class ArtifactInfoImpl implements IArtifactInfo { 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 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) { @@ -93,28 +93,32 @@ public class ArtifactInfoImpl implements IArtifactInfo { ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); generatedFromUUID = artifactFrom.getArtifactUUID(); } - ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts())); + 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) { + 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(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList()); + 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(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList()); } return requiredArtifacts; } @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 + "]"; + return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL + + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout=" + artifactTimeout + + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + + ", relatedArtifacts=" + relatedArtifacts + "]"; } - } 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 1041e584f7..bebc286592 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 @@ -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. @@ -17,20 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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_INTERNAL_SERVER_ERROR = 500; - CambriaOperationStatus operationStatus; Integer httpCode; List variables = new ArrayList<>(); @@ -82,5 +78,4 @@ public class CambriaErrorResponse { 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 3f8abccb21..425b464c4f 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 @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; +import static java.util.concurrent.TimeUnit.SECONDS; + import com.att.nsa.apiClient.credentials.ApiCredential; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.apiClient.http.HttpObjectNotFoundException; @@ -39,13 +40,6 @@ 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.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Component; - import java.io.IOException; import java.net.MalformedURLException; import java.security.GeneralSecurityException; @@ -55,25 +49,25 @@ import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; - -import static java.util.concurrent.TimeUnit.SECONDS; +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.log.wrappers.Logger; +import org.springframework.stereotype.Component; @Component("cambriaHandler") -public class CambriaHandler implements ICambriaHandler{ +public class CambriaHandler implements ICambriaHandler { private static final Logger log = Logger.getLogger(CambriaHandler.class.getName()); private static final String PARTITION_KEY = "asdc" + "aa"; private static final String SEND_NOTIFICATION = "send notification"; - private static final String CONSUMER_ID = ConfigurationManager.getConfigurationManager() - .getDistributionEngineConfiguration() - .getDistributionStatusTopic() - .getConsumerId(); - private static final boolean USE_HTTPS_WITH_DMAAP = ConfigurationManager.getConfigurationManager() - .getDistributionEngineConfiguration() - .isUseHttpsWithDmaap(); + private static final String CONSUMER_ID = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration() + .getDistributionStatusTopic().getConsumerId(); + private static final boolean USE_HTTPS_WITH_DMAAP = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration() + .isUseHttpsWithDmaap(); private final Gson gson = new Gson(); - /** * process the response error from Cambria client * @@ -81,17 +75,13 @@ public class CambriaHandler implements ICambriaHandler{ * @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; - } /** @@ -104,7 +94,6 @@ public class CambriaHandler implements ICambriaHandler{ */ 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(); @@ -113,8 +102,7 @@ public class CambriaHandler implements ICambriaHandler{ if (httpCode != null) { try { result = Integer.valueOf(httpCode); - } - catch (NumberFormatException e) { + } catch (NumberFormatException e) { log.debug("Failed to parse http code {}", httpCode); } } @@ -130,36 +118,25 @@ public class CambriaHandler implements ICambriaHandler{ */ @Override public Either, CambriaErrorResponse> getTopics(List hostSet) { - CambriaTopicManager createTopicManager = null; try { - createTopicManager = buildCambriaClient(createTopicManagerBuilder(hostSet)); - Set topics = createTopicManager.getTopics(); - if (topics == null || topics.isEmpty()) { CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND, null); return Either.right(cambriaErrorResponse); } - return Either.left(topics); - - } - catch (IOException | GeneralSecurityException e) { - + } catch (IOException | GeneralSecurityException e) { CambriaErrorResponse cambriaErrorResponse = processError(e); - log.debug("Failed to fetch topics from U-EB server", e); writeErrorToLog(cambriaErrorResponse, "getTopics", "get topics"); - return Either.right(cambriaErrorResponse); } finally { if (createTopicManager != null) { createTopicManager.close(); } } - } /** @@ -170,15 +147,11 @@ public class CambriaHandler implements ICambriaHandler{ * @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; @@ -191,16 +164,12 @@ public class CambriaHandler implements ICambriaHandler{ default: cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); } - } - else { - + } 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(); @@ -211,26 +180,23 @@ public class CambriaHandler implements ICambriaHandler{ } } } - if (!found) { cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); cambriaErrorResponse.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } - return cambriaErrorResponse; } /** * write the error to the log - * @param cambriaErrorResponse + * + * @param cambriaErrorResponse * @param methodName * @param operationDesc */ private void writeErrorToLog(CambriaErrorResponse cambriaErrorResponse, String methodName, String operationDesc) { - String httpCode = cambriaErrorResponse.getHttpCode() == null ? "" : String.valueOf(cambriaErrorResponse.getHttpCode()); - switch (cambriaErrorResponse.getOperationStatus()) { case UNKNOWN_HOST_ERROR: BeEcompErrorManager.getInstance().logBeUebUnkownHostError(methodName, httpCode); @@ -247,7 +213,6 @@ public class CambriaHandler implements ICambriaHandler{ default: break; } - } /** @@ -262,87 +227,66 @@ public class CambriaHandler implements ICambriaHandler{ * @return */ @Override - public CambriaErrorResponse createTopic(Collection hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount) { - + public CambriaErrorResponse createTopic(Collection hostSet, String apiKey, String secretKey, String topicName, int partitionCount, + int replicationCount) { CambriaTopicManager createTopicManager = null; try { - AbstractAuthenticatedManagerBuilder clientBuilder = createTopicManagerBuilder(hostSet, apiKey, secretKey); createTopicManager = buildCambriaClient(clientBuilder); - createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount); - - } - catch (HttpException | IOException | GeneralSecurityException e) { - + } catch (HttpException | IOException | GeneralSecurityException e) { log.debug("Failed to create topic {}", topicName, e); - CambriaErrorResponse cambriaErrorResponse = processError(e); - if (cambriaErrorResponse.getOperationStatus() != CambriaOperationStatus.TOPIC_ALREADY_EXIST) { writeErrorToLog(cambriaErrorResponse, "createTopic", "create topic"); } - return cambriaErrorResponse; - } finally { if (createTopicManager != null) { createTopicManager.close(); } } return new CambriaErrorResponse(CambriaOperationStatus.OK); - } + @Override - public CambriaErrorResponse unRegisterFromTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) { + public CambriaErrorResponse unRegisterFromTopic(Collection hostSet, String managerApiKey, String managerSecretKey, + String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) { String methodName = "unRegisterFromTopic"; CambriaTopicManager createTopicManager = null; try { - AbstractAuthenticatedManagerBuilder clientBuilder = createTopicManagerBuilder(hostSet, managerApiKey, managerSecretKey); - + AbstractAuthenticatedManagerBuilder clientBuilder = createTopicManagerBuilder(hostSet, managerApiKey, + managerSecretKey); createTopicManager = buildCambriaClient(clientBuilder); - if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { createTopicManager.revokeProducer(topicName, subscriberApiKey); - } - else { + } else { createTopicManager.revokeConsumer(topicName, subscriberApiKey); } - - } - catch (HttpObjectNotFoundException e) { - log.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString() - .toLowerCase(), e); + } catch (HttpObjectNotFoundException e) { + log.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); - return new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); - - } - catch (HttpException | IOException | GeneralSecurityException e) { + } catch (HttpException | IOException | GeneralSecurityException e) { log.debug("Failed to unregister {} from topic {} as producer", managerApiKey, topicName, e); CambriaErrorResponse cambriaErrorResponse = processError(e); - - writeErrorToLog(cambriaErrorResponse, methodName, "unregister from topic as " + subscriberTypeEnum - .toString() - .toLowerCase()); - + writeErrorToLog(cambriaErrorResponse, methodName, "unregister from topic as " + subscriberTypeEnum.toString().toLowerCase()); return cambriaErrorResponse; } finally { if (createTopicManager != null) { createTopicManager.close(); } } - return new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); } - private AbstractAuthenticatedManagerBuilder createTopicManagerBuilder(Collection hostSet, String managerApiKey, String managerSecretKey) { + private AbstractAuthenticatedManagerBuilder createTopicManagerBuilder(Collection hostSet, String managerApiKey, + String managerSecretKey) { AbstractAuthenticatedManagerBuilder clientBuilder = createTopicManagerBuilder(hostSet) - .authenticatedBy(managerApiKey, managerSecretKey); + .authenticatedBy(managerApiKey, managerSecretKey); if (USE_HTTPS_WITH_DMAAP) { clientBuilder = clientBuilder.usingHttps(); } - return clientBuilder; } @@ -362,47 +306,33 @@ public class CambriaHandler implements ICambriaHandler{ * @return */ @Override - public CambriaErrorResponse registerToTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) { - + public CambriaErrorResponse registerToTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, + SubscriberTypeEnum subscriberTypeEnum, String topicName) { String methodName = "registerToTopic"; CambriaTopicManager createTopicManager = null; try { - AbstractAuthenticatedManagerBuilder clientBuilder = createTopicManagerBuilder(hostSet, managerApiKey, managerSecretKey); + AbstractAuthenticatedManagerBuilder clientBuilder = createTopicManagerBuilder(hostSet, managerApiKey, + managerSecretKey); createTopicManager = buildCambriaClient(clientBuilder); - if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { createTopicManager.allowProducer(topicName, subscriberApiKey); - } - else { + } else { createTopicManager.allowConsumer(topicName, subscriberApiKey); } - - } - catch (HttpObjectNotFoundException e) { - log.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString() - .toLowerCase(), e); - + } catch (HttpObjectNotFoundException e) { + log.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); - return new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); - - } - catch (HttpException | IOException | GeneralSecurityException e) { - log.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString() - .toLowerCase(), e); + } catch (HttpException | IOException | GeneralSecurityException e) { + log.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); CambriaErrorResponse cambriaErrorResponse = processError(e); - - writeErrorToLog(cambriaErrorResponse, methodName, "register to topic as " + subscriberTypeEnum - .toString() - .toLowerCase()); - + writeErrorToLog(cambriaErrorResponse, methodName, "register to topic as " + subscriberTypeEnum.toString().toLowerCase()); return cambriaErrorResponse; } finally { if (createTopicManager != null) { createTopicManager.close(); } } - return new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); } @@ -420,24 +350,18 @@ public class CambriaHandler implements ICambriaHandler{ * @throws Exception */ @Override - 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(); + 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(); } - } /** @@ -448,7 +372,6 @@ public class CambriaHandler implements ICambriaHandler{ */ @Override public Either, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer) { - String methodName = "fetchFromTopic"; try { Iterable messages = topicConsumer.fetch(); @@ -456,19 +379,16 @@ public class CambriaHandler implements ICambriaHandler{ messages = new ArrayList<>(); } return Either.left(messages); - - } - catch (IOException e) { + } catch (IOException e) { CambriaErrorResponse cambriaErrorResponse = processError(e); log.debug("Failed to fetch from U-EB topic. error={}", e.getMessage()); writeErrorToLog(cambriaErrorResponse, methodName, "get messages from topic"); return Either.right(cambriaErrorResponse); - - } - catch (Exception e) { + } catch (Exception e) { log.debug("Failed to fetch from U-EB topic", e); BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, + HttpStatus.SC_INTERNAL_SERVER_ERROR); return Either.right(cambriaErrorResponse); } } @@ -484,42 +404,29 @@ public class CambriaHandler implements ICambriaHandler{ * @return */ @Override - public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, INotificationData data) { - + public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, + INotificationData data) { CambriaBatchingPublisher createSimplePublisher = null; - try { - String json = gson.toJson(data); log.trace("Before sending notification data {} to topic {}", json, topicName); - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build(); createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); - int result = createSimplePublisher.send(PARTITION_KEY, json); - try { SECONDS.sleep(1L); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { log.debug("Failed during sleep after sending the message.", e); Thread.currentThread().interrupt(); } - log.debug("After sending notification data to topic {}. result is {}", topicName, result); - return new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - } catch (IOException | GeneralSecurityException e) { log.debug("Failed to send notification {} to topic {} ", data, topicName, e); - CambriaErrorResponse cambriaErrorResponse = processError(e); - writeErrorToLog(cambriaErrorResponse, "sendNotification", SEND_NOTIFICATION); - return cambriaErrorResponse; - } - finally { + } finally { if (createSimplePublisher != null) { log.debug("Before closing publisher"); createSimplePublisher.close(); @@ -527,44 +434,32 @@ public class CambriaHandler implements ICambriaHandler{ } } } + @Override - public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, INotificationData data, long waitBeforeCloseTimeout) { + public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, + INotificationData data, long waitBeforeCloseTimeout) { String methodName = "sendNotificationAndClose"; CambriaBatchingPublisher createSimplePublisher; CambriaErrorResponse response; try { - String json = gson.toJson(data); log.debug("Before sending notification data {} to topic {}", json, topicName); - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build(); createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); - int result = createSimplePublisher.send(PARTITION_KEY, json); - try { Thread.sleep(1000); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { log.debug("Failed during sleep after sending the message.", e); Thread.currentThread().interrupt(); } - log.debug("After sending notification data to topic {}. result is {}", topicName, result); - - } - catch (IOException | GeneralSecurityException e) { + } catch (IOException | GeneralSecurityException e) { log.debug("Failed to send notification {} to topic {} ", data, topicName, e); - - response = processError(e); - writeErrorToLog(response, methodName, SEND_NOTIFICATION); - return response; - } - log.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout); try { List messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, SECONDS); @@ -572,75 +467,59 @@ public class CambriaHandler implements ICambriaHandler{ log.debug("Cambria client returned {} non sent messages.", messagesInQ.size()); response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); writeErrorToLog(response, methodName, SEND_NOTIFICATION); - } - else { + } else { log.debug("No message left in the queue after closing cambria publisher"); response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); } - } - catch (InterruptedException e) { + } catch (InterruptedException e) { log.debug("InterruptedException while closing cambria publisher", e); Thread.currentThread().interrupt(); response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); writeErrorToLog(response, methodName, SEND_NOTIFICATION); - } - catch (IOException e) { + } catch (IOException e) { log.debug("Failed to close cambria publisher", e); response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); writeErrorToLog(response, methodName, SEND_NOTIFICATION); } log.debug("After closing publisher"); - return response; - } + @Override public CambriaErrorResponse getApiKey(String server, String apiKey) { - CambriaErrorResponse response; List hostSet = new ArrayList<>(); hostSet.add(server); try { CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet)); createIdentityManager.getApiKey(apiKey); - response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - - } - catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) { + } catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) { log.debug("Failed to fetch api key {} from server {}", apiKey, server, e); - response = processError(e); - } - return response; } + @Override public Either createUebKeys(List hostSet) { Either result; - try { CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet)); - 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 (Exception e) { + } catch (Exception e) { log.debug("Failed to create ueb keys for servers {}", hostSet, e); - result = Either.right(processError(e)); - } - return result; } @VisibleForTesting - T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder client) throws MalformedURLException, GeneralSecurityException { + T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder client) + throws MalformedURLException, GeneralSecurityException { return 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 index 630815d26a..dd201d9b5e 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import com.att.aft.dme2.api.DME2Exception; 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 2fa6190c44..cb14ebeebe 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 @@ -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. @@ -17,9 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +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 javax.annotation.Resource; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; @@ -35,48 +44,32 @@ import org.openecomp.sdc.common.log.wrappers.Logger; 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.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.regex.Matcher; -import java.util.regex.Pattern; @Component("distributionEngine") public class DistributionEngine implements IDistributionEngine { private static final Logger logger = Logger.getLogger(DistributionEngine.class.getName()); - 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); - + 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); @Autowired private EnvironmentsEngine environmentsEngine; - @Resource private DistributionNotificationSender distributionNotificationSender; - @Resource private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - @Resource private DistributionEngineClusterHealth distributionEngineClusterHealth; - @Resource private ServiceDistributionValidation serviceDistributionValidation; - private Map envNamePerInitTask = new HashMap<>(); private Map envNamePerPollingTask = new HashMap<>(); private Map envNamePerStatus = new HashMap<>(); @Override public boolean isActive() { - if (envNamePerInitTask.isEmpty()) { return false; } - for (DistributionEngineInitTask task : envNamePerInitTask.values()) { boolean active = task.isActive(); if (!active) { @@ -89,40 +82,31 @@ public class DistributionEngine implements IDistributionEngine { @PostConstruct private void init() { logger.trace("Enter init method of DistributionEngine"); - - DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); boolean startDistributionEngine = distributionEngineConfiguration.isStartDistributionEngine(); logger.debug("Distribution engine activation parameter is {}", startDistributionEngine); if (!startDistributionEngine) { logger.info("The distribution engine is disabled"); - this.distributionEngineClusterHealth.setHealthCheckUebIsDisabled(); - return; } - boolean isValidConfig = validateConfiguration(distributionEngineConfiguration); - if (!isValidConfig) { - BeEcompErrorManager.getInstance().logBeUebSystemError(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) { 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"); } @@ -139,18 +123,16 @@ public class DistributionEngine implements IDistributionEngine { task.destroy(); } } - } /** * validate mandatory configuration parameters received + * * @param deConfiguration: distribution engine configuration * @return boolean result: true of false */ protected boolean validateConfiguration(DistributionEngineConfiguration deConfiguration) { - String methodName = "validateConfiguration"; - boolean result = isValidServers(deConfiguration.getUebServers(), methodName, "uebServers"); result = isValidParam(deConfiguration.getEnvironments(), methodName, "environments") && result; result = isValidParam(deConfiguration.getUebPublicKey(), methodName, "uebPublicKey") && result; @@ -165,38 +147,31 @@ public class DistributionEngine implements IDistributionEngine { 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; @@ -204,7 +179,6 @@ public class DistributionEngine implements IDistributionEngine { } private boolean isValidParam(String paramValue, String methodName, String paramName) { - if (StringUtils.isEmpty(paramValue)) { BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); return false; @@ -213,7 +187,6 @@ public class DistributionEngine implements IDistributionEngine { } private boolean isValidParam(List paramValue, String methodName, String paramName) { - if (CollectionUtils.isEmpty(paramValue)) { BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); return false; @@ -222,42 +195,35 @@ public class DistributionEngine implements IDistributionEngine { } 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"; + 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; } @@ -266,9 +232,7 @@ public class DistributionEngine implements IDistributionEngine { @Override public StorageOperationStatus isEnvironmentAvailable() { - String envName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); - return isEnvironmentAvailable(envName); } @@ -284,13 +248,16 @@ public class DistributionEngine implements IDistributionEngine { } @Override - public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, User modifier) { - logger.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, service.getLastUpdaterUserId(), modifier); + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, + User modifier) { + logger.debug( + "Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", + distributionId, service.getUUID(), service.getUniqueId(), envName, service.getLastUpdaterUserId(), modifier); String topicName = buildTopicName(envName); - ActionStatus notifyServiceStatus = Optional.ofNullable(environmentsEngine.getEnvironmentById(envId)) - .map(EnvironmentMessageBusData::new) - .map(messageBusData -> distributionNotificationSender.sendNotification(topicName, distributionId, messageBusData, notificationData, service, modifier)) - .orElse(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE); + ActionStatus notifyServiceStatus = Optional.ofNullable(environmentsEngine.getEnvironmentById(envId)).map(EnvironmentMessageBusData::new).map( + messageBusData -> distributionNotificationSender + .sendNotification(topicName, distributionId, messageBusData, notificationData, service, modifier)) + .orElse(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE); logger.debug("Finish notifyService. status is {}", notifyServiceStatus); return notifyServiceStatus; } @@ -306,7 +273,8 @@ public class DistributionEngine implements IDistributionEngine { 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); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, + "Environment name " + envName + " is not available. Reason : " + envErrorDec); } return status; } @@ -327,5 +295,4 @@ public class DistributionEngine implements IDistributionEngine { 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 ec58cad146..1e9899b09f 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 @@ -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. @@ -17,20 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; -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.common.api.Constants; -import org.openecomp.sdc.common.api.HealthCheckInfo; -import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; -import org.openecomp.sdc.common.log.wrappers.Logger; -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; @@ -43,69 +31,155 @@ 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; +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.log.wrappers.Logger; +import org.springframework.stereotype.Component; + @Component("distribution-engine-cluster-health") public class DistributionEngineClusterHealth { + private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck"; + private static final Logger logger = Logger.getLogger(DistributionEngineClusterHealth.class.getName()); protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck"; - //TODO use LoggerMetric instead private static final Logger healthLogger = Logger.getLogger(UEB_HEALTH_LOG_CONTEXT); - - private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck"; - boolean lastHealthState = false; - Object lockOject = new Object(); - + ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "UEB-Health-Check-Task"); + } + }); + HealthCheckScheduledTask healthCheckScheduledTask = null; private long reconnectInterval = 5; - private long healthCheckReadTimeout = 20; - - private static final Logger logger = Logger.getLogger(DistributionEngineClusterHealth.class.getName()); - private List uebServers = null; - private String publicApiKey = null; + private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNKNOWN.getHealthCheckInfo(); + private Map envNamePerStatus = null; + private ScheduledFuture scheduledFuture = null; - 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())), - UNKNOWN(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UNKNOWN, null, ClusterStatusDescription.UNKNOWN.getDescription())); - - private HealthCheckInfo healthCheckInfo; + @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"); + } - HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { - this.healthCheckInfo = healthCheckInfo; + @PreDestroy + protected void destroy() { + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; } + if (healthCheckScheduler != null) { + healthCheckScheduler.shutdown(); + } + } - public HealthCheckInfo getHealthCheckInfo() { - return healthCheckInfo; + /** + * Start health check task. + * + * @param envNamePerStatus + * @param startTask + */ + public void startHealthCheckTask(Map envNamePerStatus, boolean startTask) { + this.envNamePerStatus = envNamePerStatus; + if (startTask && this.scheduledFuture == null) { + this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); } + } + public void startHealthCheckTask(Map envNamePerStatus) { + startHealthCheckTask(envNamePerStatus, true); } - private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNKNOWN.getHealthCheckInfo(); + private void logAlarm(boolean lastHealthState) { + if (lastHealthState) { + BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR); + } else { + BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR); + } + } - private Map envNamePerStatus = null; + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } - private ScheduledFuture scheduledFuture = null; + /** + * change the health check to DISABLE + */ + public void setHealthCheckUebIsDisabled() { + healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo(); + } - ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "UEB-Health-Check-Task"); + /** + * change the health check to NOT CONFGIURED + */ + public void setHealthCheckUebConfigurationError() { + healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo(); + } + + public void setHealthCheckOkAndReportInCaseLastStateIsDown() { + if (lastHealthState) { + return; } - }); + synchronized (lockOject) { + if (!lastHealthState) { + logger.debug("Going to update health check state to available"); + lastHealthState = true; + healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); + logAlarm(lastHealthState); + } + } + } - HealthCheckScheduledTask healthCheckScheduledTask = null; + 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())), UNKNOWN( + new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UNKNOWN, null, + ClusterStatusDescription.UNKNOWN.getDescription())); + private HealthCheckInfo healthCheckInfo; - public enum ClusterStatusDescription { + HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { + this.healthCheckInfo = healthCheckInfo; + } - OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration"), UNKNOWN("U-EB cluster is currently unknown (try again in few minutes)"); + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + } + 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"), UNKNOWN("U-EB cluster is currently unknown (try again in few minutes)"); private String desc; ClusterStatusDescription(String desc) { @@ -115,24 +189,30 @@ public class DistributionEngineClusterHealth { 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. - * + *

+ * 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<>(); + /** + * 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"); + } + }); public HealthCheckScheduledTask(List uebServers) { - logger.debug("Create health check calls for servers {}", uebServers); if (uebServers != null) { for (String server : uebServers) { @@ -143,17 +223,13 @@ public class DistributionEngineClusterHealth { @Override public void run() { - healthLogger.trace("Executing UEB Health Check Task - Start"); - boolean healthStatus = verifyAtLeastOneEnvIsUp(); - if (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); @@ -169,17 +245,13 @@ public class DistributionEngineClusterHealth { } 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) { @@ -191,163 +263,45 @@ public class DistributionEngineClusterHealth { } } } - 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()); - + 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); - + healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, + healthCheckCall.getServer(), result); if (result != null && 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); + 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 && 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) { - 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) { - return; - } - synchronized (lockOject) { - if (!lastHealthState) { - 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 52b1967397..6207cd2a5a 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 @@ -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. @@ -17,19 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; 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.be.resources.data.auditing.model.DistributionTopicData; -import org.openecomp.sdc.common.log.wrappers.Logger; - import java.util.HashSet; import java.util.Set; import java.util.concurrent.Executors; @@ -38,6 +28,14 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; +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.be.resources.data.auditing.model.DistributionTopicData; +import org.openecomp.sdc.common.log.wrappers.Logger; public class DistributionEngineInitTask implements Runnable { @@ -48,26 +46,25 @@ public class DistributionEngineInitTask implements Runnable { public static final String CREATED = "CREATED"; public static final String FAILED = "FAILED"; public static final Integer HTTP_OK = 200; - + private static final Logger logger = Logger.getLogger(DistributionEngineInitTask.class.getName()); + boolean maximumRetryInterval = false; + ComponentsUtils componentsUtils = null; + DistributionEnginePollingTask distributionEnginePollingTask = null; + ScheduledFuture scheduledFuture = null; 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(); - private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); - private static final Logger logger = Logger.getLogger(DistributionEngineInitTask.class.getName()); - ScheduledFuture scheduledFuture = null; - - public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, AtomicBoolean status, ComponentsUtils componentsUtils, DistributionEnginePollingTask distributionEnginePollingTask, OperationalEnvironmentEntry environmentEntry) { + + public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, + AtomicBoolean status, ComponentsUtils componentsUtils, + DistributionEnginePollingTask distributionEnginePollingTask, OperationalEnvironmentEntry environmentEntry) { super(); this.delayBeforeStartFlow = delayBeforeStartFlow; this.deConfiguration = deConfiguration; @@ -81,26 +78,25 @@ public class DistributionEngineInitTask implements Runnable { this.environmentEntry = environmentEntry; } + public static String buildTopicName(String topicName, String environment) { + return topicName + "-" + environment.toUpperCase(); + } + 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); + 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() { @@ -140,10 +136,8 @@ public class DistributionEngineInitTask implements Runnable { @Override public void run() { - boolean result = false; result = initFlow(); - if (result) { this.stopTask(); this.status.set(true); @@ -165,12 +159,9 @@ public class DistributionEngineInitTask implements Runnable { * @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(); @@ -183,35 +174,29 @@ public class DistributionEngineInitTask implements Runnable { } else { topicsList = getTopicsRes.left().value(); } - String notificationTopic = buildTopicName(deConfiguration.getDistributionNotifTopicName(), this.envName); logger.debug("Going to handle topic {}", notificationTopic); if (!createNotificationTopicIfNotExists(topicsList, notificationTopic)) { 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); if (!createStatusTopicIfNotExists(topicsList, statusTopic)) { return false; } - CambriaErrorResponse registerConcumerStatus = registerToTopic(statusTopic, SubscriberTypeEnum.CONSUMER); - return registerConcumerStatus.getOperationStatus() == CambriaOperationStatus.OK; } private CambriaErrorResponse registerToTopic(String topicName, SubscriberTypeEnum subscriberType) { - CambriaErrorResponse registerStatus = cambriaHandler.registerToTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), environmentEntry.getUebApikey(), subscriberType, topicName); - + CambriaErrorResponse registerStatus = cambriaHandler + .registerToTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), + environmentEntry.getUebApikey(), subscriberType, topicName); String role = CONSUMER; if (subscriberType == SubscriberTypeEnum.PRODUCER) { role = PRODUCER; @@ -225,56 +210,50 @@ public class DistributionEngineInitTask implements Runnable { Integer httpCode = registerProducerStatus.getHttpCode(); String httpCodeStr = String.valueOf(httpCode); this.componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, this.envName, - DistributionTopicData.newBuilder() - .notificationTopic(notificationTopic) - .build(), - role, environmentEntry.getUebApikey(), httpCodeStr); + DistributionTopicData.newBuilder().notificationTopic(notificationTopic).build(), role, environmentEntry.getUebApikey(), httpCodeStr); } } private boolean createStatusTopicIfNotExists(Set topicsList, String topicName) { - DistributionTopicData distributionTopicData = DistributionTopicData.newBuilder() - .statusTopic(topicName) - .build(); + DistributionTopicData distributionTopicData = DistributionTopicData.newBuilder().statusTopic(topicName).build(); return createDistributionTopic(topicsList, topicName, distributionTopicData); } private boolean createNotificationTopicIfNotExists(Set topicsList, String topicName) { - - DistributionTopicData distributionTopicData = DistributionTopicData.newBuilder() - .notificationTopic(topicName) - .build(); + DistributionTopicData distributionTopicData = DistributionTopicData.newBuilder().notificationTopic(topicName).build(); return createDistributionTopic(topicsList, topicName, distributionTopicData); } private boolean createDistributionTopic(Set topicsList, String topicName, DistributionTopicData distributionTopicData) { - boolean isSucceeded = true; - if (topicsList.contains(topicName)) { if (componentsUtils != null) { - componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, ALREADY_EXISTS); + componentsUtils + .auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, ALREADY_EXISTS); } return isSucceeded; } - CambriaErrorResponse createDistribTopicStatus = cambriaHandler.createTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), topicName, deConfiguration.getCreateTopic().getPartitionCount(), - deConfiguration.getCreateTopic().getReplicationCount()); - + CambriaErrorResponse createDistribTopicStatus = cambriaHandler + .createTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), topicName, + deConfiguration.getCreateTopic().getPartitionCount(), deConfiguration.getCreateTopic().getReplicationCount()); CambriaOperationStatus status = createDistribTopicStatus.getOperationStatus(); switch (status) { case OK: if (componentsUtils != null) { - componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, CREATED); + componentsUtils + .auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, CREATED); } break; case TOPIC_ALREADY_EXIST: if (componentsUtils != null) { - componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, ALREADY_EXISTS); + componentsUtils + .auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, ALREADY_EXISTS); } break; default: if (componentsUtils != null) { - componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, FAILED); + componentsUtils + .auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, FAILED); } BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName); isSucceeded = false; @@ -283,10 +262,6 @@ public class DistributionEngineInitTask implements Runnable { return isSucceeded; } - public static String buildTopicName(String topicName, String environment) { - return topicName + "-" + environment.toUpperCase(); - } - public boolean isActive() { return this.status.get(); } 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 933d3ef4a1..124671086f 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 @@ -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. @@ -17,13 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; 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; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -34,41 +37,32 @@ import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit; -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 static final String PARTNER_NAME = "UNKNOWN"; - + private static final Logger logger = Logger.getLogger(DistributionEnginePollingTask.class.getName()); + private static LoggerSdcAudit audit = new LoggerSdcAudit(DistributionEnginePollingTask.class); + ScheduledFuture scheduledFuture = null; 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 = Logger.getLogger(DistributionEnginePollingTask.class.getName()); - private static LoggerSdcAudit audit = new LoggerSdcAudit(DistributionEnginePollingTask.class); - - ScheduledFuture scheduledFuture = null; + private ScheduledExecutorService scheduledPollingService = Executors + .newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build()); private CambriaConsumer cambriaConsumer = null; - private DistributionEngineClusterHealth distributionEngineClusterHealth = null; - private OperationalEnvironmentEntry environmentEntry; - public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, DistributionCompleteReporter distributionCompleteReporter, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth, 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(); @@ -81,7 +75,6 @@ public class DistributionEnginePollingTask implements Runnable { } public void startTask(String topicName) { - this.topicName = topicName; logger.debug("start task for polling topic {}", topicName); if (fetchTimeoutInSec < 15) { @@ -89,13 +82,12 @@ public class DistributionEnginePollingTask implements Runnable { fetchTimeoutInSec = 15; } try { - cambriaConsumer = cambriaHandler.createConsumer(environmentEntry.getDmaapUebAddress(), topicName, environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), consumerId, consumerGroup, - fetchTimeoutInSec * 1000); - + 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); @@ -117,7 +109,6 @@ public class DistributionEnginePollingTask implements Runnable { logger.debug("close consumer"); cambriaHandler.closeConsumer(cambriaConsumer); } - } public void destroy() { @@ -128,7 +119,6 @@ public class DistributionEnginePollingTask implements Runnable { @Override public void run() { logger.trace("run() method. polling queue {}", topicName); - try { // init error if (cambriaConsumer == null) { @@ -136,19 +126,19 @@ public class DistributionEnginePollingTask implements Runnable { 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); - + 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) { @@ -160,42 +150,44 @@ public class DistributionEnginePollingTask implements Runnable { 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()); + 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 occurred", e); String methodName = Object.class.getEnclosingMethod().getName(); BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); } - } private void handleDistributionNotificationMsg(DistributionStatusNotification notification, LoggerSdcAudit audit) { - componentUtils.auditDistributionStatusNotification(notification.getDistributionID(), - notification.getConsumerID(), topicName, notification.getArtifactURL(), - String.valueOf(notification.getTimestamp()), notification.getStatus().name(), - notification.getErrorReason(), audit); + componentUtils.auditDistributionStatusNotification(notification.getDistributionID(), notification.getConsumerID(), topicName, + notification.getArtifactURL(), String.valueOf(notification.getTimestamp()), notification.getStatus().name(), + notification.getErrorReason(), audit); if (notification.isDistributionCompleteNotification()) { distributionCompleteReporter.reportDistributionComplete(notification); } } private void shutdownExecutor() { - if (scheduledPollingService == null) + 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)) + if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) { logger.debug("Pool did not terminate"); + } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted @@ -204,5 +196,4 @@ public class DistributionEnginePollingTask implements Runnable { 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 1c6afe5a98..0098eac7d9 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -34,39 +33,28 @@ import org.springframework.stereotype.Component; public class DistributionNotificationSender { protected static final String DISTRIBUTION_NOTIFICATION_SENDING = "distributionNotificationSending"; - private static final Logger logger = Logger.getLogger(DistributionNotificationSender.class.getName()); - @javax.annotation.Resource protected ComponentsUtils componentUtils; private CambriaHandler cambriaHandler = new CambriaHandler(); - private DistributionEngineConfiguration deConfiguration = - ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + private DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - public ActionStatus sendNotification(String topicName, String distributionId, - EnvironmentMessageBusData messageBusData, INotificationData notificationData, Service service, - User modifier) { + public ActionStatus sendNotification(String topicName, String distributionId, EnvironmentMessageBusData messageBusData, + INotificationData notificationData, Service service, User modifier) { 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(new AuditDistributionNotificationBuilder().setTopicName(topicName) - .setDistributionId(distributionId).setStatus(status).setService(service) - .setEnvId(messageBusData.getEnvId()).setModifier(modifier) - .setWorkloadContext(notificationData.getWorkloadContext()).setTenant(messageBusData.getTenant())); - + 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( + new AuditDistributionNotificationBuilder().setTopicName(topicName).setDistributionId(distributionId).setStatus(status).setService(service) + .setEnvId(messageBusData.getEnvId()).setModifier(modifier).setWorkloadContext(notificationData.getWorkloadContext()) + .setTenant(messageBusData.getTenant())); long endTime = System.currentTimeMillis(); - if (logger.isDebugEnabled()) { - logger.debug("After building and publishing artifacts object. Total took {} milliseconds", - endTime - startTime); + logger.debug("After building and publishing artifacts object. Total took {} milliseconds", endTime - startTime); } - return convertCambriaResponse(status); } @@ -74,20 +62,15 @@ public class DistributionNotificationSender { if (this.componentUtils != null) { Integer httpCode = builder.getStatus().getHttpCode(); String httpCodeStr = String.valueOf(httpCode); - String desc = getDescriptionFromErrorResponse(builder.getStatus()); - - this.componentUtils.auditDistributionNotification(builder.getService().getUUID(), - builder.getService().getName(), "Service", builder.getService().getVersion(), builder.getModifier(), - builder.getEnvId(), builder.getService().getLifecycleState().name(), builder.getTopicName(), - builder.getDistributionId(), desc, httpCodeStr, builder.getWorkloadContext(), builder.getTenant()); + this.componentUtils.auditDistributionNotification(builder.getService().getUUID(), builder.getService().getName(), "Service", + builder.getService().getVersion(), builder.getModifier(), builder.getEnvId(), builder.getService().getLifecycleState().name(), + builder.getTopicName(), builder.getDistributionId(), desc, httpCodeStr, builder.getWorkloadContext(), builder.getTenant()); } } private String getDescriptionFromErrorResponse(CambriaErrorResponse status) { - CambriaOperationStatus operationStatus = status.getOperationStatus(); - switch (operationStatus) { case OK: return "OK"; @@ -103,14 +86,11 @@ public class DistributionNotificationSender { 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; @@ -126,9 +106,6 @@ public class DistributionNotificationSender { return ActionStatus.OBJECT_NOT_FOUND; default: return ActionStatus.GENERAL_ERROR; - } } - - } 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 430b8bec24..f05cc760e5 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; public class DistributionStatusNotification { @@ -78,11 +77,13 @@ public class DistributionStatusNotification { } public boolean isDistributionCompleteNotification() { - return DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK == status || DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR == status; + return DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK == status + || DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR == status; } @Override public String toString() { - return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]"; + 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 65aa18ee97..64c1963c0b 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 @@ -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. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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, 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 index 4fb4122984..0f4836ea1c 100644 --- 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 @@ -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. @@ -17,33 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import com.att.nsa.mr.client.MRBatchingPublisher; import com.att.nsa.mr.client.MRClientFactory; import com.att.nsa.mr.client.MRConsumer; import fj.data.Either; +import java.io.File; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Properties; import org.onap.sdc.security.SecurityUtil; import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; import org.openecomp.sdc.be.config.DmaapProducerConfiguration; import org.openecomp.sdc.common.log.wrappers.Logger; 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 = Logger.getLogger(DmaapClientFactory.class.getName()); /** * Creates DMAAP consumer according to received parameters + * * @param parameters * @return an instance object of type MRConsumer * @throws IOException @@ -53,9 +53,10 @@ public class DmaapClientFactory { logger.info("MRConsumer created for topic {}", parameters.getTopic()); return consumer; } - + /** * Creates DMAAP consumer according to received parameters + * * @param parameters * @return an instance object of type MRConsumer * @throws IOException @@ -69,8 +70,8 @@ public class DmaapClientFactory { private Properties buildProperties(DmaapConsumerConfiguration parameters) throws GeneralSecurityException, IOException { Properties props = new Properties(); - Either passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword() ); - if (passkey.isRight()){ + 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())); @@ -79,34 +80,30 @@ public class DmaapClientFactory { 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("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("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("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())); - props.setProperty("AFT_DME2_SSL_ENABLE", Boolean.toString(parameters.isAftDme2SslEnable())); props.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", Boolean.toString(parameters.isAftDme2ClientIgnoreSslConfig())); props.setProperty("AFT_DME2_CLIENT_KEYSTORE", parameters.getAftDme2ClientKeystore()); props.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", parameters.getAftDme2ClientKeystorePassword()); props.setProperty("AFT_DME2_CLIENT_SSL_CERT_ALIAS", parameters.getAftDme2ClientSslCertAlias()); - - String dme2PreferredRouterFilePath = parameters.getDme2preferredRouterFilePath(); ensureFileExists(dme2PreferredRouterFilePath); props.setProperty("DME2preferredRouterFilePath", dme2PreferredRouterFilePath); - props.setProperty("TransportType", "DME2"); props.setProperty("SubContextPath", "/"); props.setProperty("MethodType", "GET"); @@ -116,15 +113,14 @@ public class DmaapClientFactory { props.setProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", ""); props.setProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS", ""); props.setProperty("sessionstickinessrequired", "no"); - return props; } - private Properties buildProducerProperties(DmaapProducerConfiguration parameters) throws GeneralSecurityException, IOException { + private Properties buildProducerProperties(DmaapProducerConfiguration parameters) throws GeneralSecurityException, IOException { logger.info("The DmaapProducerConfiguration is {} ", parameters); Properties props = new Properties(); - Either passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword() ); - if (passkey.isRight()){ + 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())); @@ -136,7 +132,7 @@ public class DmaapClientFactory { props.setProperty("routeOffer", parameters.getRouteOffer()); props.setProperty("Protocol", parameters.getProtocol()); props.setProperty("username", parameters.getCredential().getUsername()); - props.setProperty("password", passkey.left().value() ); + props.setProperty("password", passkey.left().value()); props.setProperty("contenttype", parameters.getContenttype()); props.setProperty("host", parameters.getHosts()); props.setProperty("topic", parameters.getTopic()); @@ -147,13 +143,11 @@ public class DmaapClientFactory { 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())); - props.setProperty("AFT_DME2_SSL_ENABLE", Boolean.toString(parameters.isAftDme2SslEnable())); props.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", Boolean.toString(parameters.isAftDme2ClientIgnoreSslConfig())); props.setProperty("AFT_DME2_CLIENT_KEYSTORE", parameters.getAftDme2ClientKeystore()); props.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", parameters.getAftDme2ClientKeystorePassword()); props.setProperty("AFT_DME2_CLIENT_SSL_CERT_ALIAS", parameters.getAftDme2ClientSslCertAlias()); - String dme2PreferredRouterFilePath = parameters.getDme2preferredRouterFilePath(); ensureFileExists(dme2PreferredRouterFilePath); props.setProperty("DME2preferredRouterFilePath", dme2PreferredRouterFilePath); @@ -165,22 +159,19 @@ public class DmaapClientFactory { props.setProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", ""); props.setProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS", ""); props.setProperty("sessionstickinessrequired", "no"); - - props.setProperty("maxBatchSize","1"); - props.setProperty("maxAgeMs","250"); - props.setProperty("partition","1"); - props.setProperty("MessageSentThreadOccurance","10"); - props.setProperty("Authorization","Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2"); - + props.setProperty("maxBatchSize", "1"); + props.setProperty("maxAgeMs", "250"); + props.setProperty("partition", "1"); + props.setProperty("MessageSentThreadOccurance", "10"); + props.setProperty("Authorization", "Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2"); return props; } private void ensureFileExists(String filePath) throws IOException { File file = new File(filePath); - if(file.createNewFile()) { + if (file.createNewFile()) { logger.info("The file {} has been created on the disk", file.getAbsolutePath()); - } - else{ + } 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 index 681b3021bb..81fa3ddf1b 100644 --- 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 @@ -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. @@ -17,10 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import com.att.nsa.mr.client.MRConsumer; +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; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; @@ -28,33 +32,28 @@ import org.openecomp.sdc.common.log.wrappers.Logger; 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. + * Allows consuming DMAAP topic according to received consumer parameters Allows processing received messages. */ @Service public class DmaapConsumer { + private static final String LOG_PARTNER_NAME = "SDC.BE"; private static final Logger logger = Logger.getLogger(DmaapClientFactory.class.getName()); + private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler(); private final ExecutorFactory executorFactory; private final DmaapClientFactory dmaapClientFactory; private final DmaapHealth dmaapHealth; - private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler(); + /** * Allows to create an object of type DmaapConsumer + * * @param executorFactory * @param dmaapClientFactory * @param dmaapHealth */ @Autowired - public DmaapConsumer(ExecutorFactory executorFactory, DmaapClientFactory dmaapClientFactory, - DmaapHealth dmaapHealth) { + public DmaapConsumer(ExecutorFactory executorFactory, DmaapClientFactory dmaapClientFactory, DmaapHealth dmaapHealth) { this.executorFactory = executorFactory; this.dmaapClientFactory = dmaapClientFactory; this.dmaapHealth = dmaapHealth; @@ -62,26 +61,26 @@ public class DmaapConsumer { /** * 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(); + 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; mdcFieldsHandler.addInfoForErrorAndDebugLogging(LOG_PARTNER_NAME); try { Iterable messages = consumer.fetch(); - isTopicAvailable = true ; + isTopicAvailable = true; if (messages != null) { for (String msg : messages) { logger.info("The DMAAP message {} received. The topic is {}.", msg, topic); @@ -89,12 +88,10 @@ public class DmaapConsumer { } } //successfully fetched - } - catch (Exception e) { + } catch (Exception e) { logger.error("The exception occurred upon fetching DMAAP message", e); } - dmaapHealth.report( isTopicAvailable ); + 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 index 0515b08b2e..96ac07063d 100644 --- 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 @@ -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. @@ -17,20 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Component; +import static org.apache.commons.lang3.StringUtils.countMatches; +import static org.apache.commons.lang3.StringUtils.isNotBlank; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_ENGINE; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.io.IOException; import java.net.InetAddress; import java.net.URI; @@ -40,76 +32,78 @@ 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.countMatches; -import static org.apache.commons.lang3.StringUtils.isNotBlank; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_ENGINE; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +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.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; @Component("dmaapHealth") public class DmaapHealth { - private static final String DMAAP_HEALTH_LOG_CONTEXT = "dmaap.healthcheck"; private static final String DMAAP_HEALTH_CHECK_STR = "dmaapHealthCheck"; private static final Logger log = Logger.getLogger(DmaapHealth.class.getName()); private static final Logger logHealth = Logger.getLogger(DMAAP_HEALTH_LOG_CONTEXT); + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 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 HealthCheckScheduledTask healthCheckScheduledTask = null; private ScheduledFuture scheduledFuture = null; - private DmaapConsumerConfiguration configuration = 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 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); } - } - - public enum DmaapStatusDescription { - OK("OK"), UNAVAILABLE("Dmaap is not available"),DOWN("DOWN"), NOT_CONFIGURED("Dmaap configuration is missing/wrong "); + //endregion - private String desc; - DmaapStatusDescription(String desc) { - this.desc = desc; - } - public String getDescription() { - return desc; + //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)"); } @PostConstruct public DmaapHealth init() { - if(!ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration().isActive()){ + if (!ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration().isActive()) { log.debug("Dmaap health check task disabled"); return this; } log.trace("Enter init method of Dmaap health"); - synchronized (DmaapHealth.class){ + synchronized (DmaapHealth.class) { this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration(); - Integer pollingInterval = configuration.getPollingInterval(); - if (pollingInterval != null && pollingInterval!=0) { + 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 + this.healthCheckScheduledTask = new HealthCheckScheduledTask(configuration); //what is the representation? csv? delimiter? json or other startHealthCheckTask(true); } log.trace("Exit init method of DistributionEngineClusterHealth"); @@ -133,110 +127,122 @@ public class DmaapHealth { * @param startTask */ private void startHealthCheckTask(boolean startTask) { - synchronized (DmaapHealth.class){ + synchronized (DmaapHealth.class) { if (startTask && this.scheduledFuture == null) { - this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS); + this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); } } } - void report(Boolean isUp){ - if (reportedHealthState == null) + void report(Boolean isUp) { + if (reportedHealthState == null) { reportedHealthState = new AtomicBoolean(isUp); + } reportedHealthState.set(isUp); } - public HealthCheckInfo getHealthCheckInfo() { return healthCheckInfo; } + public enum HealthCheckInfoResult { + // @formatter:off + 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())); + // @formatter:on + + private HealthCheckInfo healthCheckInfo; + + HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { + this.healthCheckInfo = healthCheckInfo; + } + + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + } + + public enum DmaapStatusDescription { + // @formatter:off + OK("OK"), + UNAVAILABLE("Dmaap is not available"), + DOWN("DOWN"), + NOT_CONFIGURED("Dmaap configuration is missing/wrong "); + // @formatter:on + + private String desc; + + DmaapStatusDescription(String desc) { + this.desc = desc; + } + + public String getDescription() { + return desc; + } + + } + /** * Health Check Task Scheduler - infinite check. */ public class HealthCheckScheduledTask implements Runnable { - private final DmaapConsumerConfiguration config; + private static final int TIMEOUT = 8192; + private final DmaapConsumerConfiguration config; - HealthCheckScheduledTask(final DmaapConsumerConfiguration config){ + HealthCheckScheduledTask(final DmaapConsumerConfiguration config) { this.config = config; } + @Override public void run() { logHealth.trace("Executing Dmaap Health Check Task - Start"); boolean prevIsReachable; boolean reachable; //first try simple ping - try{ - if ( reportedHealthState != null ){ + try { + if (reportedHealthState != null) { reachable = reportedHealthState.get(); + } else { + reachable = false; } - else{ - reachable = false; - } - prevIsReachable = lastHealthState.getAndSet( reachable ); + 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 ); + } 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() ); + if (prevIsReachable != lastHealthState.get()) { + logAlarm(lastHealthState.get()); + } } - /** * @deprecated (health is reported outside from EnvironmentEngine consumer fetch) */ @Deprecated - public boolean isICMPReachable( ) throws IOException{ - try{ + 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 InetAddress.getByName(hostname).isReachable(TIMEOUT); + } catch (URISyntaxException e) { + log.debug("{} - malformed host configuration -> ", DMAAP_HEALTH_CHECK_STR, e); } return false; } private void logAlarm(boolean lastHealthState) { - try{ - if ( lastHealthState ) { - BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery( DMAAP_HEALTH_CHECK_STR ); + try { + if (lastHealthState) { + BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery(DMAAP_HEALTH_CHECK_STR); } else { - BeEcompErrorManager.getInstance().logDmaapHealthCheckError( DMAAP_HEALTH_CHECK_STR ); + BeEcompErrorManager.getInstance().logDmaapHealthCheckError(DMAAP_HEALTH_CHECK_STR); } - }catch( Exception e ){ - log.debug("cannot logAlarm -> {}" ,e ); - } - } - - } - - 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 (Exception e) { + log.debug("cannot logAlarm -> {}", e); } - }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 index 208fb84d25..b4934f7fe1 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; /** @@ -62,6 +61,4 @@ public class DmaapNotificationDataImpl implements IDmaapNotificationData, IDmaap 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 index 5bb579eaa6..e68a4866db 100644 --- 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 @@ -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. @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; -import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; - import java.util.ArrayList; import java.util.List; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; /** * a pojo which holds all the necessary data to communicate with the message bus @@ -32,13 +30,9 @@ import java.util.List; public class EnvironmentMessageBusData { private List dmaaPuebEndpoints; - private String uebPublicKey; - private String uebPrivateKey; - private String envId; - private String tenant; public EnvironmentMessageBusData() { @@ -91,5 +85,4 @@ public class EnvironmentMessageBusData { 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 index 97d2440c11..315ba1de14 100644 --- 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 @@ -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. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.glassfish.jersey.internal.guava.Predicates.not; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.runMethodWithTimeOut; + import com.att.aft.dme2.api.DME2Exception; import com.att.aft.dme2.iterator.DME2EndpointIterator; import com.att.aft.dme2.iterator.domain.DME2EndpointReference; @@ -29,6 +32,18 @@ import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fj.data.Either; +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 javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.components.distribution.engine.IDmaapNotificationData.DmaapActionEnum; @@ -52,23 +67,6 @@ import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Service; -import javax.annotation.PostConstruct; -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.glassfish.jersey.internal.guava.Predicates.not; -import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.runMethodWithTimeOut; - /** * Allows to consume DMAAP topic and handle received notifications */ @@ -79,13 +77,7 @@ public class EnvironmentsEngine implements INotificationHandler { private static final String UNKNOWN = "Unknown"; private static final Logger log = Logger.getLogger(EnvironmentsEngine.class.getName()); private static final String LOG_PARTNER_NAME = "SDC.BE"; - private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); - - private Map environments = new HashMap<>(); - private Map envNamePerStatus = new HashMap<>(); - private Map envNamePerPollingTask = new HashMap<>(); - private Map envNamePerInitTask = new HashMap<>(); - + private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler(); private final DmaapConsumer dmaapConsumer; private final OperationalEnvironmentDao operationalEnvironmentDao; private final DME2EndpointIteratorCreator epIterCreator; @@ -94,9 +86,16 @@ public class EnvironmentsEngine implements INotificationHandler { private final CambriaHandler cambriaHandler; private final DistributionEngineClusterHealth distributionEngineClusterHealth; private final DistributionCompleteReporter distributionCompleteReporter; - private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler(); + private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); + private Map environments = new HashMap<>(); + private Map envNamePerStatus = new HashMap<>(); + private Map envNamePerPollingTask = new HashMap<>(); + private Map envNamePerInitTask = new HashMap<>(); - public EnvironmentsEngine(DmaapConsumer dmaapConsumer, OperationalEnvironmentDao operationalEnvironmentDao, DME2EndpointIteratorCreator epIterCreator, AaiRequestHandler aaiRequestHandler, ComponentsUtils componentUtils, CambriaHandler cambriaHandler, DistributionEngineClusterHealth distributionEngineClusterHealth, 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; @@ -115,12 +114,12 @@ public class EnvironmentsEngine implements INotificationHandler { environments = populateEnvironments(); createUebTopicsForEnvironments(); initDmeGlobalConfig(); - if(!configurationManager.getConfiguration().getDmaapConsumerConfiguration().isActive()){ + if (!configurationManager.getConfiguration().getDmaapConsumerConfiguration().isActive()) { log.info("Environments engine is disabled"); return; } - dmaapConsumer.consumeDmaapTopic(this::handleMessage, - (t, e) -> log.error("An error occurred upon consuming topic by Dmaap consumer client: ", e)); + dmaapConsumer + .consumeDmaapTopic(this::handleMessage, (t, e) -> log.error("An error occurred upon consuming topic by Dmaap consumer client: ", e)); log.info("Environments engine has been initialized."); } catch (Exception e) { log.error("An error occurred upon consuming topic by Dmaap consumer client.", e); @@ -128,28 +127,31 @@ public class EnvironmentsEngine implements INotificationHandler { } private void initDmeGlobalConfig() { - DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration(); + DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration() + .getDmaapConsumerConfiguration(); if (dmaapConsumerParams == null) { log.warn("cannot read dmaap configuration file,DME might not be initialized properly"); return; } System.setProperty("AFT_ENVIRONMENT", dmaapConsumerParams.getAftEnvironment()); // AFTPRD for production - System.setProperty("AFT_LATITUDE", dmaapConsumerParams.getLatitude() != null ? dmaapConsumerParams.getLatitude().toString() : "1.0"); // Replace with actual latitude - System.setProperty("AFT_LONGITUDE", dmaapConsumerParams.getLongitude() != null ? dmaapConsumerParams.getLongitude().toString() : "1.0"); // Replace with actual longitude + + System.setProperty("AFT_LATITUDE", + dmaapConsumerParams.getLatitude() != null ? dmaapConsumerParams.getLatitude().toString() : "1.0"); // Replace with actual latitude + + System.setProperty("AFT_LONGITUDE", + dmaapConsumerParams.getLongitude() != null ? dmaapConsumerParams.getLongitude().toString() : "1.0"); // Replace with actual longitude } - public void connectUebTopicTenantIsolation(OperationalEnvironmentEntry opEnvEntry, - AtomicBoolean status, - Map envNamePerInitTask, Map envNamePerPollingTask) { + 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) { + public void connectUebTopicForDistributionConfTopic(String envName, AtomicBoolean status, + Map envNamePerInitTask, + Map envNamePerPollingTask) { connectUebTopic(environments.get(envName), status, envNamePerInitTask, envNamePerPollingTask); - } /** @@ -163,33 +165,26 @@ public class EnvironmentsEngine implements INotificationHandler { 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); + .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 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(); + DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration() + .getDmaapConsumerConfiguration(); Supplier supplier = () -> handleMessageLogic(notification); - Either eitherTimeOut = runMethodWithTimeOut(supplier, - dmaapConsumerParams.getTimeLimitForNotificationHandleMs()); - + Either eitherTimeOut = runMethodWithTimeOut(supplier, dmaapConsumerParams.getTimeLimitForNotificationHandleMs()); boolean result; if (eitherTimeOut.isRight()) { result = false; @@ -203,15 +198,10 @@ public class EnvironmentsEngine implements INotificationHandler { 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); - + IDmaapNotificationData notificationData = gsonObj.fromJson(notification, DmaapNotificationDataImpl.class); + IDmaapAuditNotificationData auditNotificationData = gsonObj.fromJson(notification, DmaapNotificationDataImpl.class); AuditingActionEnum actionEnum; switch (notificationData.getAction()) { case CREATE: @@ -227,11 +217,9 @@ public class EnvironmentsEngine implements INotificationHandler { actionEnum = AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION; break; } - componentUtils.auditEnvironmentEngine(actionEnum, - notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(), - notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(), - auditNotificationData.getTenantContext()); - + componentUtils.auditEnvironmentEngine(actionEnum, notificationData.getOperationalEnvironmentId(), + notificationData.getOperationalEnvironmentType().getEventTypenName(), notificationData.getAction().getActionName(), + auditNotificationData.getOperationalEnvironmentName(), auditNotificationData.getTenantContext()); if (errorWrapper.isEmpty()) { validateNotification(errorWrapper, notificationData, auditNotificationData); } @@ -239,16 +227,12 @@ public class EnvironmentsEngine implements INotificationHandler { if (errorWrapper.isEmpty()) { saveEntryWithInProgressStatus(errorWrapper, opEnvEntryWrapper, notificationData); } - if (errorWrapper.isEmpty()) { buildOpEnv(errorWrapper, opEnvEntryWrapper.getInnerElement()); } - } catch (Exception e) { - log.debug("handle message for operational environment failed for notification: {} with error :{}", - notification, e.getMessage(), e); + log.debug("handle message for operational environment failed for notification: {} with error :{}", notification, e.getMessage(), e); errorWrapper.setInnerElement(false); - } return errorWrapper.isEmpty(); } @@ -274,28 +258,23 @@ public class EnvironmentsEngine implements INotificationHandler { 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); @@ -314,24 +293,24 @@ public class EnvironmentsEngine implements INotificationHandler { 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"); - log.invoke(opEnvEntry.getEnvironmentId(), "retrieveUebAddressesFromAftDme", opEnvEntry.getStatus(), EnvironmentsEngine.class.getName(), errorWrapper.toString() ); + log.invoke(opEnvEntry.getEnvironmentId(), "retrieveUebAddressesFromAftDme", opEnvEntry.getStatus(), EnvironmentsEngine.class.getName(), + errorWrapper.toString()); try { boolean isKeyFieldsValid = !isEmpty(opEnvEntry.getTenant()) && !isEmpty(opEnvEntry.getEcompWorkloadContext()); if (isKeyFieldsValid) { String opEnvKey = map2OpEnvKey(opEnvEntry); List uebHosts = discoverUebHosts(opEnvKey); opEnvEntry.setDmaapUebAddress(uebHosts.stream().collect(Collectors.toSet())); - log.invokeReturn(opEnvEntry.getEnvironmentId(), "retrieveUebAddressesFromAftDme", opEnvEntry.getStatus(), "SDC-BE", errorWrapper.toString() ); + log.invokeReturn(opEnvEntry.getEnvironmentId(), "retrieveUebAddressesFromAftDme", opEnvEntry.getStatus(), "SDC-BE", + errorWrapper.toString()); } else { errorWrapper.setInnerElement(false); log.debug("Can Not Build AFT DME Key from workLoad & Tenant Fields."); } - } catch (Exception e) { errorWrapper.setInnerElement(false); log.error("Failed to retrieve Ueb Addresses From DME. ", e); @@ -340,10 +319,8 @@ public class EnvironmentsEngine implements INotificationHandler { 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); + 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"); @@ -356,8 +333,7 @@ public class EnvironmentsEngine implements INotificationHandler { void retrieveOpEnvInfoFromAAI(Wrapper errorWrapper, OperationalEnvironmentEntry opEnvEntry) { log.debug("handle message - Get Env Info From A&AI"); - Either eitherOperationalEnvInfo = getOperationalEnvById( - opEnvEntry.getEnvironmentId()); + Either eitherOperationalEnvInfo = getOperationalEnvById(opEnvEntry.getEnvironmentId()); if (eitherOperationalEnvInfo.isRight()) { errorWrapper.setInnerElement(false); log.debug("handle message - failed to retrieve details from A&AI"); @@ -368,7 +344,8 @@ public class EnvironmentsEngine implements INotificationHandler { } } - void saveEntryWithInProgressStatus(Wrapper errorWrapper, Wrapper opEnvEntryWrapper, IDmaapNotificationData notificationData) { + 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 @@ -377,16 +354,12 @@ public class EnvironmentsEngine implements INotificationHandler { 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); + Either eitherOpEnv = operationalEnvironmentDao.get(opEnvId); if (eitherOpEnv.isLeft()) { final OperationalEnvironmentEntry opEnvEntry = eitherOpEnv.left().value(); if (StringUtils.equals(opEnvEntry.getStatus(), EnvironmentStatusEnum.IN_PROGRESS.getName())) { @@ -397,11 +370,9 @@ public class EnvironmentsEngine implements INotificationHandler { 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); + log.debug("failed to retrieve operationa environment with id:{} cassandra error was :{}", opEnvId, operationStatus); } } - } void validateActionType(Wrapper errorWrapper, IDmaapNotificationData notificationData) { @@ -420,21 +391,18 @@ public class EnvironmentsEngine implements INotificationHandler { 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()); + 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); + log.debug("handle message saving operational environmet failed for id :{} with error : {}", entry.getEnvironmentId(), saveStaus); } } @@ -443,7 +411,6 @@ public class EnvironmentsEngine implements INotificationHandler { String environment = configurationManager.getConfiguration().getDmaapConsumerConfiguration().getEnvironment(); String lookupURI = String.format(lookupUriFormat, opEnvKey, environment); log.debug("DME2 GRM URI: {}", lookupURI); - List uebHosts = new LinkedList<>(); DME2EndpointIterator iterator = epIterCreator.create(lookupURI); // Beginning iteration @@ -453,7 +420,6 @@ public class EnvironmentsEngine implements INotificationHandler { log.debug("DME returns EP with UEB host {}, UEB port: {}", dmeEndpoint.getHost(), dmeEndpoint.getPort()); uebHosts.add(dmeEndpoint.getHost()); } - return uebHosts; } @@ -470,34 +436,28 @@ public class EnvironmentsEngine implements INotificationHandler { private OperationalEnvironmentEntry readEnvFromConfig() { OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); - DistributionEngineConfiguration distributionEngineConfiguration = configurationManager - .getDistributionEngineConfiguration(); + 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; + String envName = + distributionEngineConfiguration.getEnvironments().size() == 1 ? distributionEngineConfiguration.getEnvironments().get(0) : UNKNOWN; entry.setEnvironmentId(envName); entry.setIsProduction(true); - if (log.isDebugEnabled()) { log.debug("Enviroment read from configuration: {}", entry); } - return entry; } private Map getEnvironmentsFromDb() { Either, CassandraOperationStatus> opEnvResult = operationalEnvironmentDao - .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED); - + .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED); if (opEnvResult.isLeft()) { Map resultMap = opEnvResult.left().value().stream() - .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity())); + .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity())); resultMap.forEach((key, value) -> log.debug("Enviroment loaded from DB: {}", value)); return resultMap; } else { @@ -508,9 +468,7 @@ public class EnvironmentsEngine implements INotificationHandler { } void createUebTopicsForEnvironments() { - environments.values().stream() - .filter(not(OperationalEnvironmentEntry::getIsProduction)) - .forEach(this::createUebTopicsForEnvironment); + environments.values().stream().filter(not(OperationalEnvironmentEntry::getIsProduction)).forEach(this::createUebTopicsForEnvironment); } public void createUebTopicsForEnvironment(OperationalEnvironmentEntry opEnvEntry) { @@ -518,7 +476,6 @@ public class EnvironmentsEngine implements INotificationHandler { log.debug("Create Environment {} on UEB Topic.", envId); AtomicBoolean status = new AtomicBoolean(false); envNamePerStatus.put(envId, status); - connectUebTopicTenantIsolation(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask); } @@ -532,21 +489,16 @@ public class EnvironmentsEngine implements INotificationHandler { } public OperationalEnvironmentEntry getEnvironmentByDmaapUebAddress(List dmaapUebAddress) { - return environments.values().stream() - .filter(e -> e.getDmaapUebAddress().stream() - .filter(dmaapUebAddress::contains).findAny().isPresent()) - .findFirst() - .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST,dmaapUebAddress.toString())); + return environments.values().stream().filter(e -> e.getDmaapUebAddress().stream().filter(dmaapUebAddress::contains).findAny().isPresent()) + .findFirst() + .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST, dmaapUebAddress.toString())); } - - 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) { @@ -554,8 +506,8 @@ public class EnvironmentsEngine implements INotificationHandler { return Either.right(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } else { - log.debug("Get \"{}\" operational environment failed with statusCode: {}, description: {}", id, - resp.getStatusCode(), resp.getDescription()); + log.debug("Get \"{}\" operational environment failed with statusCode: {}, description: {}", id, resp.getStatusCode(), + resp.getDescription()); return Either.right(resp.getStatusCode()); } } @@ -574,6 +526,5 @@ public class EnvironmentsEngine implements INotificationHandler { 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 index d0c1edc9fa..ee718f177b 100644 --- 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 @@ -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. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.openecomp.sdc.common.log.wrappers.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; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + @Component("executorFactory") /** * Allows to create next kinds of single thread executors: SingleThreadExecutor and SingleThreadScheduledExecutor @@ -38,26 +37,22 @@ public class ExecutorFactory { private static final Logger logger = Logger.getLogger(EnvironmentsEngine.class.getName()); - public ExecutorService create(String name, UncaughtExceptionHandler exceptionHandler){ + 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){ + 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)); + (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(); + 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 b4919dfbfe..ba51ba69bf 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 @@ -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. @@ -17,12 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; public interface IArtifactInfo { - /** Artifact File name */ + /** + * Artifact File name + */ String getArtifactName(); /** @@ -33,12 +34,9 @@ public interface IArtifactInfo { String 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 + * 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(); @@ -57,5 +55,4 @@ public interface IArtifactInfo { * Artifact description */ String getArtifactDescription(); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ICambriaHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ICambriaHandler.java index 60ab20d292..b887e7f0a7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ICambriaHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ICambriaHandler.java @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import com.att.nsa.apiClient.credentials.ApiCredential; import com.att.nsa.cambria.client.CambriaConsumer; import fj.data.Either; - import java.util.Collection; import java.util.List; import java.util.Set; @@ -31,15 +29,28 @@ import java.util.Set; public interface ICambriaHandler { Either, CambriaErrorResponse> getTopics(List hostSet); - CambriaErrorResponse createTopic(Collection hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount); - CambriaErrorResponse unRegisterFromTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName); - CambriaErrorResponse registerToTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName); - CambriaConsumer createConsumer(Collection hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception; + + CambriaErrorResponse createTopic(Collection hostSet, String apiKey, String secretKey, String topicName, int partitionCount, + int replicationCount); + + CambriaErrorResponse unRegisterFromTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, + SubscriberTypeEnum subscriberTypeEnum, String topicName); + + CambriaErrorResponse registerToTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, + SubscriberTypeEnum subscriberTypeEnum, String topicName); + + CambriaConsumer createConsumer(Collection hostSet, String topicName, String apiKey, String secretKey, String consumerId, + String consumerGroup, int timeoutMS) throws Exception; + Either, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer); - CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, INotificationData data); - CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, INotificationData data, long waitBeforeCloseTimeout); - CambriaErrorResponse getApiKey(String server, String apiKey); - Either createUebKeys(List hostSet); + CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, + INotificationData data); + + CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, + INotificationData data, long waitBeforeCloseTimeout); + CambriaErrorResponse getApiKey(String server, String apiKey); + + Either createUebKeys(List hostSet); } 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 2136463f79..f08043cf76 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import java.util.List; 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 index 23bccac0db..f41055c354 100644 --- 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 @@ -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. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 index ee90867d02..bc0ffbb881 100644 --- 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 @@ -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. @@ -17,12 +17,12 @@ * 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(); @@ -30,12 +30,13 @@ public interface IDmaapNotificationData { DmaapActionEnum getAction(); enum DmaapActionEnum { + // @formatter:off DELETE("Delete"), CREATE("Create"), UPDATE("Update"), - UNKONW("UNKONW") + UNKONW("UNKONW"); + // @formatter:on - ; private String actionName; private DmaapActionEnum(String actionName) { @@ -46,15 +47,17 @@ public interface IDmaapNotificationData { return actionName; } - public static DmaapActionEnum findByName(String actionName){ + public static DmaapActionEnum findByName(String actionName) { return getEnumValueByFieldValue(actionName, DmaapActionEnum.values(), DmaapActionEnum::getActionName, UNKONW, false); } } enum OperationaEnvironmentTypeEnum { + // @formatter:off ECOMP("ECOMP"), - UNKONW("UNKONW") - ; + UNKONW("UNKONW"); + // @formatter:on + private String eventTypenName; private OperationaEnvironmentTypeEnum(String eventTypenName) { @@ -65,8 +68,9 @@ public interface IDmaapNotificationData { return eventTypenName; } - public static OperationaEnvironmentTypeEnum findByName(String operationalEnvironmentTypeName){ - return getEnumValueByFieldValue(operationalEnvironmentTypeName, OperationaEnvironmentTypeEnum.values(), OperationaEnvironmentTypeEnum::getEventTypenName, UNKONW, false); + 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 d66f8f92f1..a1f2299289 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 @@ -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. @@ -17,12 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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.
@@ -31,76 +31,81 @@ public interface INotificationData { */ String getDistributionID(); - /** Logical Service Name. */ - String getServiceName(); + void setDistributionID(String distributionId); /** - * Service Version.
- * Two dot (".") separated digit blocks.
- * Ex. : "2.0" + * Logical Service Name. */ - String getServiceVersion(); + String getServiceName(); /** - * 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 + * Logical Service Name. */ - String getServiceUUID(); + void setServiceName(String serviceName); /** - * Service description + * Service Version.
Two dot (".") separated digit blocks.
Ex. : "2.0" */ - String getServiceDescription(); + String getServiceVersion(); /** - * ServiceInvariant UUID + * Service Version.
Two dot (".") separated digit blocks.
Ex. : "2.0" */ - 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); + void setServiceVersion(String serviceVersion); /** - * Service Version.
- * Two dot (".") separated digit blocks.
- * Ex. : "2.0" + * 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 setServiceVersion(String serviceVersion); + String getServiceUUID(); /** - * 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 + * 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 + */ + String getServiceDescription(); + /** * Service Description */ void setServiceDescription(String serviceDescription); + /** + * ServiceInvariant UUID + */ + String getServiceInvariantUUID(); + /** * ServiceInvariant UUID */ void setServiceInvariantUUID(String serviceInvariantUuid); - /** List of the Resource Instances */ + /** + * List of the resource instances + */ + List getResources(); + + /** + * List of the Resource Instances + */ void setResources(List resource); - /** List of the Resource Instances */ + /** + * List of the artifacts + */ + List getServiceArtifacts(); + + /** + * List of the Resource Instances + */ void setServiceArtifacts(List artifacts); - void setWorkloadContext(String workloadContext); + String getWorkloadContext(); + 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 index 49f40840cb..46a6d25435 100644 --- 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 @@ -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. @@ -17,15 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 deac8751b3..d731b74f49 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 @@ -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. @@ -17,15 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; public interface IResourceArtifactInfo extends IArtifactInfo { - /** resource name */ + /** + * resource name + */ String getResourceName(); - /** resource version */ + /** + * resource version + */ String getResourceVersion(); /** @@ -35,5 +38,4 @@ public interface IResourceArtifactInfo extends IArtifactInfo { * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 */ String getResourceUUID(); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IServiceArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IServiceArtifactInfo.java index e102f742ac..910cff7d75 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IServiceArtifactInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IServiceArtifactInfo.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; public interface IServiceArtifactInfo extends IArtifactInfo { 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 9c478e7d9b..c4b51ffaac 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 @@ -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. @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; -import org.openecomp.sdc.be.model.ComponentInstance; - import java.util.List; +import org.openecomp.sdc.be.model.ComponentInstance; public class JsonContainerResourceInstance { + private String resourceInstanceName; private String resourceName; private String resourceVersion; @@ -46,14 +45,15 @@ public class JsonContainerResourceInstance { 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) + if (resourceInstance.getOriginType() != null) { this.resoucreType = resourceInstance.getOriginType().getValue(); + } this.resourceUUID = resourceInstance.getComponentUid(); this.artifacts = artifacts; this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID(); @@ -141,8 +141,9 @@ public class JsonContainerResourceInstance { @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 + "]"; + return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + + resourceVersion + ", resoucreType=" + resoucreType + ", 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 1db67a9581..21738b1efd 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import java.util.List; @@ -39,33 +38,33 @@ public class NotificationDataImpl implements INotificationData { return distributionID; } + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } + @Override public String getServiceName() { return serviceName; } + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + @Override public String getServiceVersion() { return serviceVersion; } + public void setServiceVersion(String serviceVersion) { + this.serviceVersion = 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; } @@ -77,25 +76,23 @@ public class NotificationDataImpl implements INotificationData { public void setServiceDescription(String serviceDescription) { this.serviceDescription = serviceDescription; } + @Override - public String getWorkloadContext() { return workloadContext; } + public String getWorkloadContext() { + return workloadContext; + } @Override - public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; } + 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 + '\'' + - '}'; + return "NotificationDataImpl{" + "distributionID='" + distributionID + '\'' + ", serviceName='" + serviceName + '\'' + ", serviceVersion='" + + serviceVersion + '\'' + ", serviceUUID='" + serviceUUID + '\'' + ", serviceDescription='" + serviceDescription + '\'' + + ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' + ", resources=" + resources + ", serviceArtifacts=" + serviceArtifacts + + ", workloadContext='" + workloadContext + '\'' + '}'; } @Override @@ -106,7 +103,6 @@ public class NotificationDataImpl implements INotificationData { @Override public void setResources(List resources) { this.resources = resources; - } @Override @@ -118,7 +114,6 @@ public class NotificationDataImpl implements INotificationData { @Override public void setServiceArtifacts(List serviceArtifacts) { this.serviceArtifacts = serviceArtifacts; - } @Override @@ -130,5 +125,4 @@ public class NotificationDataImpl implements INotificationData { 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 4a12cec213..48b4d0c060 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 @@ -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. @@ -17,50 +17,44 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig; -import org.openecomp.sdc.common.log.wrappers.Logger; - 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 org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig; +import org.openecomp.sdc.common.log.wrappers.Logger; public class NotificationExecutorService { private static final Logger logger = Logger.getLogger(NotificationExecutorService.class.getName()); public ExecutorService createExcecutorService(DistributionNotificationTopicConfig distributionNotificationTopic) { - Integer minThreadPoolSize = distributionNotificationTopic.getMinThreadPoolSize(); if (minThreadPoolSize == null) { minThreadPoolSize = 0; } - Integer maxThreadPoolSize = distributionNotificationTopic.getMaxThreadPoolSize(); if (maxThreadPoolSize == null) { maxThreadPoolSize = 10; } - ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); threadFactoryBuilder.setNameFormat("distribution-notification-thread-%d"); ThreadFactory threadFactory = threadFactoryBuilder.build(); - return new ThreadPoolExecutor(minThreadPoolSize, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), threadFactory); } 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"); @@ -73,5 +67,4 @@ public class NotificationExecutorService { Thread.currentThread().interrupt(); } } - } 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 19a857a115..86090e4e76 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; public class ResourceArtifactInfoImpl extends ArtifactInfoImpl implements IResourceArtifactInfo { @@ -52,7 +51,7 @@ public class ResourceArtifactInfoImpl extends ArtifactInfoImpl implements IResou @Override public String toString() { - return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID + super.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 1d626805f6..c9503ac31f 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; public class ServiceArtifactInfoImpl extends ArtifactInfoImpl implements IServiceArtifactInfo { @@ -26,5 +25,4 @@ public class ServiceArtifactInfoImpl extends ArtifactInfoImpl implements IServic 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 ef43c43bf5..2d43e9febc 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 @@ -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. @@ -17,10 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -39,34 +43,53 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - @Component("serviceDistributionArtifactsBuilder") public class ServiceDistributionArtifactsBuilder { private static final Logger logger = Logger.getLogger(ServiceDistributionArtifactsBuilder.class.getName()); - private static final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; private static final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; private static final String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s"; - + private final ToscaOperationFacade toscaOperationFacade; @javax.annotation.Resource InterfaceLifecycleOperation interfaceLifecycleOperation; - @javax.annotation.Resource ArtifactOperation artifactOperation; - private final ToscaOperationFacade toscaOperationFacade; - @Autowired public ServiceDistributionArtifactsBuilder(ToscaOperationFacade toscaOperationFacade) { this.toscaOperationFacade = toscaOperationFacade; } + /** + * 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; + } + public InterfaceLifecycleOperation getInterfaceLifecycleOperation() { return interfaceLifecycleOperation; } @@ -76,13 +99,11 @@ public class ServiceDistributionArtifactsBuilder { } private String resolveWorkloadContext(String workloadContext) { - return workloadContext != null ? workloadContext : - ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext(); + 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()); @@ -91,70 +112,62 @@ public class ServiceDistributionArtifactsBuilder { notificationData.setServiceDescription(service.getDescription()); notificationData.setServiceInvariantUUID(service.getInvariantUUID()); workloadContext = resolveWorkloadContext(workloadContext); - if (workloadContext!=null){ + 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()); - + //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()){ + if (toscaTemplateArtifactOptl.isPresent()) { extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get()); } - Optional toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service); - if(toscaCsarArtifactOptl.isPresent()){ + 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(); + //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(); + //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)); + 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())); + 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); } } @@ -167,20 +180,19 @@ public class ServiceDistributionArtifactsBuilder { } private List convertToArtifactsInfoImpl(Service service, ComponentInstance resourceInstance) { - List artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance)); + List artifacts = ArtifactInfoImpl + .convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance)); 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()); } @@ -191,62 +203,23 @@ public class ServiceDistributionArtifactsBuilder { 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 + * @param the service + * @return boolean */ public boolean verifyServiceContainsDeploymentArtifacts(Service service) { if (MapUtils.isNotEmpty(service.getDeploymentArtifacts())) { @@ -261,7 +234,6 @@ public class ServiceDistributionArtifactsBuilder { } private boolean isContainsPayload(Map deploymentArtifacts) { - return deploymentArtifacts != null && deploymentArtifacts.values().stream().anyMatch(ArtifactDefinition::checkEsIdExist); + 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 3477648dbd..0de3d3eb60 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 @@ -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. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; public enum SubscriberTypeEnum { - 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 bed0aaecc1..d28592d376 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 @@ -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. @@ -17,24 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; -import org.openecomp.sdc.common.log.wrappers.Logger; - import java.util.concurrent.Callable; +import org.openecomp.sdc.common.log.wrappers.Logger; public class UebHealthCheckCall implements Callable { + private static final Logger healthLogger = Logger.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT); + private static final Logger logger = Logger.getLogger(UebHealthCheckCall.class.getName()); CambriaHandler cambriaHandler = new CambriaHandler(); - String server; String publicApiKey; - private static final Logger healthLogger = Logger.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT); - - private static final Logger logger = Logger.getLogger(UebHealthCheckCall.class.getName()); - public UebHealthCheckCall(String server, String publicApiKey) { super(); this.server = server; @@ -43,24 +38,20 @@ public class UebHealthCheckCall implements Callable { @Override public Boolean call() { - healthLogger.trace("Going to run health check towards ueb server {}", server); - boolean result = false; CambriaErrorResponse cambriaErrorResponse = cambriaHandler.getApiKey(server, publicApiKey); - 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); + logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server, + cambriaErrorResponse.httpCode); result = true; + } else { + logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to false", server, + cambriaErrorResponse.httpCode); } - else { - logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to false", server, cambriaErrorResponse.httpCode); - } - - 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; } @@ -75,5 +66,4 @@ public class UebHealthCheckCall implements Callable { 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 c566c1c0ee..9222da0105 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 @@ -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. @@ -17,29 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -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.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +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; public class VfModuleArtifactPayload { private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription; private Boolean isBase; private List artifacts; - private Map< String, Object> properties; + private Map properties; public VfModuleArtifactPayload(GroupDefinition group) { vfModuleModelName = group.getName(); @@ -47,11 +45,9 @@ public class VfModuleArtifactPayload { vfModuleModelVersion = group.getVersion(); vfModuleModelUUID = group.getGroupUUID(); vfModuleModelDescription = group.getDescription(); - artifacts = group.getArtifactsUuid(); // Base Value is set from properties setBaseValue(group); - } public VfModuleArtifactPayload(GroupInstance group) { @@ -61,38 +57,41 @@ public class VfModuleArtifactPayload { vfModuleModelUUID = group.getGroupUUID(); vfModuleModelCustomizationUUID = group.getCustomizationUUID(); vfModuleModelDescription = group.getDescription(); - artifacts = new ArrayList<>(group.getArtifactsUuid() != null ? group.getArtifactsUuid() : new LinkedList<>()); artifacts.addAll(group.getGroupInstanceArtifactsUuid() != null ? group.getGroupInstanceArtifactsUuid() : new LinkedList<>()); - // Base Value is set from properties setBaseValue(group); - - if(group.convertToGroupInstancesProperties() != null) + if (group.convertToGroupInstancesProperties() != null) { setProperties(group.convertToGroupInstancesProperties()); + } + } + + 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 void setBaseValue(GroupInstance group) { if (group.convertToGroupInstancesProperties() != null) { - Optional findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + 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(); + 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; } @@ -101,21 +100,12 @@ public class VfModuleArtifactPayload { 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(PropertyDataDefinition::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); + this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)) + .collect(Collectors.toMap(PropertyDataDefinition::getName, x -> x.getValue() == null ? "" : x.getValue())); } } 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 index f5b5e2fa92..12760318f9 100644 --- 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 @@ -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. @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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", - }) +@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 index 7e6a4d83a1..4ef627f7e9 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine.report; import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification; @@ -25,5 +24,4 @@ import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNot 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 index 5cb8a26912..d753e64d3f 100644 --- 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 @@ -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. @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine.report; +import javax.annotation.Resource; 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 { @@ -34,6 +32,7 @@ public class MsoDistributionCompleteReporter implements DistributionCompleteRepo @Override public void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification) { - msoClient.notifyDistributionComplete(distributionStatusNotification.getDistributionID(), distributionStatusNotification.getStatus(), distributionStatusNotification.getErrorReason()); + 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 index 391c6c6968..dd23e2d4b5 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine.rest; /** 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 index fb0310bf7c..92ece131a8 100644 --- 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 @@ -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. @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.distribution.engine.rest; import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; +import java.util.Properties; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.eclipse.jetty.util.URIUtil; @@ -39,40 +39,40 @@ import org.openecomp.sdc.common.http.config.HttpClientConfig; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import java.util.Properties; - @Component public class MSORestClient { - private static final Logger logger = Logger.getLogger(MSORestClient.class.getName()); - private static final Gson gson = new Gson(); @VisibleForTesting static final String DISTRIBUTIONS_RESOURCE_CONFIG_PARAM = "distributions"; - + private static final Logger logger = Logger.getLogger(MSORestClient.class.getName()); + private static final Gson gson = new Gson(); private ExternalServiceConfig serviceConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig(); public MSORestClient() { HttpClientConfig httpClientConfig = serviceConfig.getHttpClientConfig(); - int numOfRetries = httpClientConfig.getNumOfRetries(); - if ( numOfRetries > 0 ) { + int numOfRetries = httpClientConfig.getNumOfRetries(); + if (numOfRetries > 0) { httpClientConfig.setRetryHandler(RetryHandlers.getDefault(numOfRetries)); } serviceConfig.getHttpClientConfig().setEnableMetricLogging(true); } - public HttpResponse notifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) { + public HttpResponse notifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, + String errReason) { try { return doNotifyDistributionComplete(distributionId, distributionStatusEnum, errReason); - } - catch(HttpExecuteException e) { + } 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()); + 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()); return response; } @@ -89,5 +89,4 @@ public class MSORestClient { 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 index c532ee979e..a90ebf9b3c 100644 --- 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 @@ -17,12 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.health; +import static java.lang.String.format; +import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; +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.HC_COMPONENT_BE; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CASSANDRA; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_PRODUCER; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ECOMP_PORTAL; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_JANUSGRAPH; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ON_BOARDING; +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; + import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.annotations.VisibleForTesting; +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.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +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.openecomp.sdc.be.catalog.impl.DmaapProducerHealth; @@ -47,34 +72,6 @@ import org.openecomp.sdc.common.util.HealthCheckUtil; 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.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static java.lang.String.format; -import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; -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.HC_COMPONENT_BE; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CASSANDRA; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_PRODUCER; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ECOMP_PORTAL; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_JANUSGRAPH; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ON_BOARDING; -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 { @@ -84,10 +81,10 @@ public class HealthCheckBusinessLogic { private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s"; private static final Logger log = Logger.getLogger(HealthCheckBusinessLogic.class.getName()); private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil(); - private final ScheduledExecutorService healthCheckScheduler = newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "BE-Health-Check-Task")); + private final ScheduledExecutorService healthCheckScheduler = newSingleThreadScheduledExecutor( + (Runnable r) -> new Thread(r, "BE-Health-Check-Task")); private HealthCheckScheduledTask healthCheckScheduledTask = null; private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler(); - @Resource private JanusGraphGenericDao janusGraphGenericDao; @Resource @@ -100,7 +97,6 @@ public class HealthCheckBusinessLogic { private CassandraHealthCheck cassandraHealthCheck; @Resource private PortalHealthCheckBuilder portalHealthCheck; - @Autowired private SwitchoverDetector switchoverDetector; private volatile List prevBeHealthCheckInfos = null; @@ -108,77 +104,60 @@ public class HealthCheckBusinessLogic { @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(); return healthCheckInfo.getHealthCheckStatus() != DOWN; } public Pair> getBeHealthCheckInfosStatus() { Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration(); - return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()), prevBeHealthCheckInfos); + return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()), + prevBeHealthCheckInfos); } private List getBeHealthCheckInfos() { - log.trace("In getBeHealthCheckInfos"); - List healthCheckInfos = new ArrayList<>(); - //Dmaap HealthCheckInfo info; if ((info = getDmaapHealthCheck()) != null) { healthCheckInfos.add(info); } - //DmaapProducer healthCheckInfos.add(getDmaapProducerHealthCheck()); - // BE healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_BE, UP, getAppVersion(), "OK")); - // JanusGraph healthCheckInfos.add(getJanusGraphHealthCheck()); - // Distribution Engine healthCheckInfos.add(distributionEngineClusterHealth.getHealthCheckInfo()); - //Cassandra healthCheckInfos.add(getCassandraHealthCheck()); - // Amdocs healthCheckInfos.add(getHostedComponentsBeHealthCheck(HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl())); - - //ECOMP Portal + //ECOMP Portal healthCheckInfos.add(portalHealthCheck.getHealthCheckInfo()); - //CADI healthCheckInfos.add(CADIHealthCheck.getCADIHealthCheckInstance().getCADIStatus()); - return healthCheckInfos; } private HealthCheckInfo getDmaapHealthCheck() { HealthCheckInfo healthCheckInfo = null; - if(ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration().isActive()){ + if (ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration().isActive()) { String appVersion = getAppVersion(); dmaapHealth.getHealthCheckInfo().setVersion(appVersion); healthCheckInfo = dmaapHealth.getHealthCheckInfo(); } else { - log.debug("Dmaap health check disabled"); + log.debug("Dmaap health check disabled"); } return healthCheckInfo; } @@ -200,7 +179,6 @@ public class HealthCheckBusinessLogic { String description; boolean isJanusGraphUp; HealthCheckInfo healthCheckInfo = new HealthCheckInfo(HC_COMPONENT_JANUSGRAPH, DOWN, null, null); - try { isJanusGraphUp = janusGraphGenericDao.isGraphOpen(); } catch (Exception e) { @@ -213,7 +191,6 @@ public class HealthCheckBusinessLogic { description = "OK"; healthCheckInfo.setDescription(description); healthCheckInfo.setHealthCheckStatus(HealthCheckInfo.HealthCheckStatus.UP); - } else { description = "JanusGraph graph is down"; healthCheckInfo.setDescription(description); @@ -222,11 +199,9 @@ public class HealthCheckBusinessLogic { } private HealthCheckInfo getCassandraHealthCheck() { - String description; boolean isCassandraUp = false; HealthCheckInfo healthCheckInfo = new HealthCheckInfo(HC_COMPONENT_CASSANDRA, DOWN, null, null); - try { isCassandraUp = cassandraHealthCheck.getCassandraStatus(); } catch (Exception e) { @@ -252,13 +227,11 @@ public class HealthCheckBusinessLogic { 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) && !componentName.equals(HC_COMPONENT_ECOMP_PORTAL)) { String response = httpResponse.getResponse(); log.trace("{} Health Check response: {}", componentName, response); @@ -274,7 +247,6 @@ public class HealthCheckBusinessLogic { } else { log.trace("{} Health Check Response code: {}", componentName, statusCode); } - if (statusCode != SC_OK) { healthCheckStatus = DOWN; description = getDescription(componentName, aggDescription); @@ -283,7 +255,6 @@ public class HealthCheckBusinessLogic { healthCheckStatus = UP; description = "OK"; } - } catch (Exception e) { log.error("{} unexpected response: ", componentName, e); healthCheckStatus = DOWN; @@ -312,9 +283,8 @@ public class HealthCheckBusinessLogic { private String getDescription(String componentName, String aggDescription) { String description; - description = aggDescription.length() > 0 - ? aggDescription - : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still 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. return description; } @@ -333,16 +303,13 @@ public class HealthCheckBusinessLogic { @PreDestroy protected void destroy() { - if (scheduledFuture != null) { scheduledFuture.cancel(true); scheduledFuture = null; } - if (healthCheckScheduler != null) { healthCheckScheduler.shutdown(); } - } private void logAlarm(String componentChangedMsg) { @@ -354,18 +321,15 @@ public class HealthCheckBusinessLogic { } 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)); - + 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 updateHealthCheckStatusMap(currentValues, prevValues); @@ -373,34 +337,30 @@ public class HealthCheckBusinessLogic { result = isHealthStatusChanged(result, currentValues, prevValues); } } - } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) { result = false; } else { writeLogAlarm(prevBeHealthCheckInfos); result = true; } - return result; } private void writeLogAlarm(List prevBeHealthCheckInfos) { - logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null")); + logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", + prevBeHealthCheckInfos == null ? "true" : "null")); } private boolean isHealthStatusChanged(boolean result, Map currentValues, Map prevValues) { 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))); @@ -419,40 +379,35 @@ public class HealthCheckBusinessLogic { 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))); } } + @VisibleForTesting String buildOnBoardingHealthCheckUrl() { - Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding(); if (onboardingConfig != null) { - return String.format(hcUrl, onboardingConfig.getProtocol(), onboardingConfig.getHost(), - onboardingConfig.getPort(),onboardingConfig.getHealthCheckUri()); + return String.format(hcUrl, onboardingConfig.getProtocol(), onboardingConfig.getHost(), onboardingConfig.getPort(), + onboardingConfig.getHealthCheckUri()); } log.error("Onboarding health check configuration is missing."); return null; } public class HealthCheckScheduledTask implements Runnable { + @Override public void run() { mdcFieldsHandler.addInfoForErrorAndDebugLogging(LOG_PARTNER_NAME); Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration(); log.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); } @@ -465,8 +420,5 @@ public class HealthCheckBusinessLogic { BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR); } } - - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/PortalHealthCheckBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/PortalHealthCheckBuilder.java index f9281e1ef2..732bfbffa5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/PortalHealthCheckBuilder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/PortalHealthCheckBuilder.java @@ -17,10 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.health; +import static org.apache.http.HttpStatus.SC_OK; +import static org.onap.portalsdk.core.onboarding.util.CipherUtil.decryptPKC; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ECOMP_PORTAL; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP; + import com.google.common.annotations.VisibleForTesting; +import java.security.InvalidParameterException; +import java.util.Base64; +import java.util.Properties; +import java.util.UUID; +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 javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import org.apache.commons.lang.StringUtils; import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; @@ -39,25 +56,6 @@ import org.openecomp.sdc.common.http.config.Timeouts; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import java.security.InvalidParameterException; -import java.util.Base64; -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import static org.apache.http.HttpStatus.SC_OK; -import static org.onap.portalsdk.core.onboarding.util.CipherUtil.decryptPKC; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ECOMP_PORTAL; -import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; -import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP; - @Component("portalHealthCheckBusinessLogic") public class PortalHealthCheckBuilder { @@ -68,23 +66,20 @@ public class PortalHealthCheckBuilder { private static final String PORTAL_ERROR = HC_COMPONENT_ECOMP_PORTAL + " responded with %s status code"; private String decryptedPortalUser; private String decryptedPortalPass; - private EcompPortalConfig configuration = null ; + private EcompPortalConfig configuration = null; private long healthCheckReadTimeout = 20; private long reconnectInterval = 5; - private HealthCheckScheduledTask healthCheckScheduledTask = null ; + private HealthCheckScheduledTask healthCheckScheduledTask = null; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private ScheduledFuture scheduledFuture = null; - private HealthCheckInfo healthCheckInfo = new HealthCheckInfo - (HC_COMPONENT_ECOMP_PORTAL, HealthCheckStatus.DOWN, null, CONFIG_IS_MISSING, null); + private HealthCheckInfo healthCheckInfo = new HealthCheckInfo(HC_COMPONENT_ECOMP_PORTAL, HealthCheckStatus.DOWN, null, CONFIG_IS_MISSING, null); @VisibleForTesting PortalHealthCheckBuilder init(EcompPortalConfig configuration) throws CipherUtilException { log.trace("Enter init method of Portal healthcheck"); - decryptedPortalUser = decryptPKC - (getPortalProperty(PortalPropertiesEnum.USER.value())); - decryptedPortalPass = decryptPKC - (getPortalProperty(PortalPropertiesEnum.PASSWORD.value())); - synchronized (PortalHealthCheckBuilder.class){ + decryptedPortalUser = decryptPKC(getPortalProperty(PortalPropertiesEnum.USER.value())); + decryptedPortalPass = decryptPKC(getPortalProperty(PortalPropertiesEnum.PASSWORD.value())); + synchronized (PortalHealthCheckBuilder.class) { if (configuration != null) { Integer pollingInterval = configuration.getPollingInterval(); if (pollingInterval != null && pollingInterval != 0) { @@ -96,8 +91,7 @@ public class PortalHealthCheckBuilder { } this.healthCheckScheduledTask = new HealthCheckScheduledTask(configuration); startHealthCheckTask(true); - } - else { + } else { log.error("ECOMP Portal health check configuration is missing."); } } @@ -110,7 +104,6 @@ public class PortalHealthCheckBuilder { return init(ConfigurationManager.getConfigurationManager().getConfiguration().getEcompPortal()); } - @PreDestroy protected void destroy() { if (scheduledFuture != null) { @@ -128,9 +121,9 @@ public class PortalHealthCheckBuilder { * @param startTask */ private void startHealthCheckTask(boolean startTask) { - synchronized (PortalHealthCheckBuilder.class){ + synchronized (PortalHealthCheckBuilder.class) { if (startTask && this.scheduledFuture == null) { - this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS); + this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); } } } @@ -148,6 +141,7 @@ public class PortalHealthCheckBuilder { * Health Check Task Scheduler - infinite check. */ public class HealthCheckScheduledTask implements Runnable { + private final EcompPortalConfig config; String healthCheckUrl = buildPortalHealthCheckUrl(); HealthCheckStatus healthCheckStatus = DOWN; @@ -155,9 +149,10 @@ public class PortalHealthCheckBuilder { String description; final int timeout = 3000; - HealthCheckScheduledTask(final EcompPortalConfig config){ + HealthCheckScheduledTask(final EcompPortalConfig config) { this.config = config; } + @Override public void run() { if (healthCheckUrl != null) { @@ -177,7 +172,6 @@ public class PortalHealthCheckBuilder { } else { description = CONFIG_IS_MISSING; } - healthCheckInfo.setHealthCheckStatus(healthCheckStatus); healthCheckInfo.setDescription(description); } @@ -195,19 +189,16 @@ public class PortalHealthCheckBuilder { final String hcUrl = "%s://%s:%s%s"; Configuration.EcompPortalConfig configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getEcompPortal(); if (configuration != null) { - return String.format(hcUrl, configuration.getProtocol(), configuration.getHost(), - configuration.getPort(), configuration.getHealthCheckUri()); + return String + .format(hcUrl, configuration.getProtocol(), configuration.getHost(), configuration.getPort(), configuration.getHealthCheckUri()); } log.error("ECOMP Portal health check configuration is missing."); return null; } - private Properties createHeaders(){ + private Properties createHeaders() { Properties headers = new Properties(); - String encodedBasicAuthCred = Base64.getEncoder() - .encodeToString((decryptedPortalUser + ":" + - decryptedPortalPass) - .getBytes()); + String encodedBasicAuthCred = Base64.getEncoder().encodeToString((decryptedPortalUser + ":" + decryptedPortalPass).getBytes()); 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()); @@ -226,5 +217,4 @@ public class PortalHealthCheckBuilder { public EcompPortalConfig getConfiguration() { return ConfigurationManager.getConfigurationManager().getConfiguration().getEcompPortal(); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java index 9206dcb52e..2fbcabe99a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java @@ -16,53 +16,55 @@ package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractResourceInfo; import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractTemplateInfo; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.Component; +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.model.Service; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; -import org.openecomp.sdc.be.model.operations.api.*; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; +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.InterfaceLifecycleOperation; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - @Getter @Setter @org.springframework.stereotype.Component("abstractTemplateBusinessLogic") public class AbstractTemplateBusinessLogic extends BaseBusinessLogic { private static final String INITIAL_VERSION = "0.1"; - private static final Logger log = Logger.getLogger(AbstractTemplateBusinessLogic.class); - - @Autowired - ServiceDistributionValidation serviceDistributionValidation; - @Autowired protected ServiceImportManager serviceImportManager; - @Autowired protected ServiceBusinessLogic serviceBusinessLogic; + @Autowired + ServiceDistributionValidation serviceDistributionValidation; @Autowired - public AbstractTemplateBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, + public AbstractTemplateBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); } public Either getServiceAbstractStatus(List componentList) { @@ -70,48 +72,45 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic { if (componentList == null || componentList.isEmpty()) { return Either.left(abstractTemplateInfo); } - for (Component curr : componentList) { Service service = (Service) curr; List componentInstances = service.getComponentInstances(); List componentInstancesRelations = service.getComponentInstancesRelations(); abstractTemplateInfo.setServiceUniqueId(service.getUniqueId()); String serviceUniqueId = abstractTemplateInfo.getServiceUniqueId(); - Either isAbstractResourceData = getEveryServiceAbstractStatus(componentInstances, abstractTemplateInfo, componentInstancesRelations, serviceUniqueId); + Either isAbstractResourceData = getEveryServiceAbstractStatus(componentInstances, abstractTemplateInfo, + componentInstancesRelations, serviceUniqueId); if (isAbstractResourceData.isRight()) { return Either.right(isAbstractResourceData.right().value()); } } - return Either.left(abstractTemplateInfo); } - private Either getEveryServiceAbstractStatus(List componentInstances, AbstractTemplateInfo abstractTemplateInfo, - List componentInstancesRelations, String serviceUniqueId) { + private Either getEveryServiceAbstractStatus(List componentInstances, + AbstractTemplateInfo abstractTemplateInfo, + List componentInstancesRelations, + String serviceUniqueId) { Map> uuidDuplicatesMap = new HashMap<>(); List abstractResourceInfoList = new ArrayList<>(); Boolean isContainAbstractResource = false; - for (ComponentInstance componentInstance : componentInstances) { String componentUid = componentInstance.getComponentUid(); String invariantUUID, resourceUUID; if (!uuidDuplicatesMap.containsKey(componentUid)) { - Either eitherResource = toscaOperationFacade - .getToscaElement(componentInstance.getComponentUid()); + Either eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); if (eitherResource.isRight()) { - log.debug("getEveryServiceAbstractStatus: Failed getting resource with UUid: {}", - componentInstance.getComponentUid()); + log.debug("getEveryServiceAbstractStatus: Failed getting resource with UUid: {}", componentInstance.getComponentUid()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(eitherResource.right().value()); return Either.right(responseFormat); } else { final Resource resource = eitherResource.left().value(); invariantUUID = resource.getInvariantUUID(); resourceUUID = resource.getUUID(); - ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, - invariantUUID); + ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); - - isContainAbstractResource = getResourceAbstractStatus(resource, isContainAbstractResource, componentInstancesRelations, serviceUniqueId,abstractResourceInfoList); + isContainAbstractResource = getResourceAbstractStatus(resource, isContainAbstractResource, componentInstancesRelations, + serviceUniqueId, abstractResourceInfoList); } } } @@ -120,40 +119,41 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic { return Either.left(isContainAbstractResource); } - private boolean getResourceAbstractStatus(Resource resource,Boolean isContainAbstractResource, List componentInstancesRelations, - String serviceUniqueId,List abstractResourceInfoList) { + private boolean getResourceAbstractStatus(Resource resource, Boolean isContainAbstractResource, + List componentInstancesRelations, String serviceUniqueId, + List abstractResourceInfoList) { boolean isAbstract = getIsAbstract(resource.getCategories()); log.debug("before if isAbstract,get resource:{}", resource); if (isAbstract) { - log.debug("getResourceAbstractStatus: resource {} with id {} ,NormalizedName:{},isAbstract{} is abstract resource", - resource.getName(), resource.getUUID(), resource.getNormalizedName(), true); + log.debug("getResourceAbstractStatus: resource {} with id {} ,NormalizedName:{},isAbstract{} is abstract resource", resource.getName(), + resource.getUUID(), resource.getNormalizedName(), true); isContainAbstractResource = true; AbstractResourceInfo abstractResourceInfo = getAbstractResourceInfo(resource, componentInstancesRelations, serviceUniqueId); abstractResourceInfoList.add(abstractResourceInfo); } else { - log.debug("getResourceAbstractStatus:resource {} ,with id {} isAbstract{} is missing the isAbstract parameter", - resource.getName(), resource.getUUID(),false); + log.debug("getResourceAbstractStatus:resource {} ,with id {} isAbstract{} is missing the isAbstract parameter", resource.getName(), + resource.getUUID(), false); } return isContainAbstractResource; } - private AbstractResourceInfo getAbstractResourceInfo(Resource resource,List componentInstancesRelations,String serviceUniqueId){ + private AbstractResourceInfo getAbstractResourceInfo(Resource resource, List componentInstancesRelations, + String serviceUniqueId) { AbstractResourceInfo abstractResourceInfo = new AbstractResourceInfo(); abstractResourceInfo.setAbstractResourceUUid(resource.getUUID()); abstractResourceInfo.setAbstractResourceName(resource.getName()); abstractResourceInfo.setAbstractResourceUniqueId(resource.getUniqueId()); String uniqueId = serviceUniqueId + "." + resource.getUniqueId() + "." + resource.getNormalizedName(); - List resourceComponentInstancesRelations = new ArrayList<>(); - log.debug("get serviceUniqueId:{},get UniqueId:{},get NormalizedName:{}", - serviceUniqueId, resource.getUniqueId(), resource.getNormalizedName()); + log.debug("get serviceUniqueId:{},get UniqueId:{},get NormalizedName:{}", serviceUniqueId, resource.getUniqueId(), + resource.getNormalizedName()); log.debug("get is Abstract,componentInstancesRelations:{}", componentInstancesRelations); for (RequirementCapabilityRelDef componentInstancesRelation : componentInstancesRelations) { log.debug("for componentInstancesRelation,get componentInstancesRelation:{}", componentInstancesRelation); String toNode = componentInstancesRelation.getToNode(); String fromNode = componentInstancesRelation.getFromNode(); - log.debug("for componentInstancesRelation,get fromNode:{},uniqueId:{},ToNode:{},Relationships:{}", - fromNode,uniqueId,toNode,componentInstancesRelation.getRelationships()); + log.debug("for componentInstancesRelation,get fromNode:{},uniqueId:{},ToNode:{},Relationships:{}", fromNode, uniqueId, toNode, + componentInstancesRelation.getRelationships()); if (toNode.toUpperCase().contains(uniqueId.toUpperCase()) || fromNode.toUpperCase().contains(uniqueId.toUpperCase())) { RequirementCapabilityRelDef resourceComponentInstancesRelation = new RequirementCapabilityRelDef(); log.debug("fromNode contains name,get componentInstancesRelation:{}", componentInstancesRelation); @@ -173,8 +173,7 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic { boolean anAbstract = false; if (categories != null && !categories.isEmpty()) { CategoryDefinition categoryDef = categories.get(0); - if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName() - .equals(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME)) { + if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME)) { SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0); if (subCategoryDef != null && subCategoryDef.getName().equals(ImportUtils.Constants.ABSTRACT_SUBCATEGORY)) { anAbstract = true; 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 index 70ec37ce48..87ef16f163 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.model.Service; @@ -26,6 +25,7 @@ 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; 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 ee6878e7d7..c3efa610fc 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 @@ -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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.List; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -48,57 +48,47 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -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 final Logger log = Logger.getLogger(AdditionalInformationBusinessLogic.class.getName()); private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}"; - private final AdditionalInformationOperation additionalInformationOperation; @Autowired - public AdditionalInformationBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - AdditionalInformationOperation additionalInformationOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public AdditionalInformationBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + AdditionalInformationOperation additionalInformationOperation, + ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.additionalInformationOperation = additionalInformationOperation; } /** * Create new additional information on resource/service on graph + * * @param nodeType * @param resourceId * @param additionalInfoParameterInfo * @param userId * @return Either */ - public Either createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) { - + public Either createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, + AdditionalInfoParameterInfo additionalInfoParameterInfo, + String userId) { validateUserExists(userId); 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 != StorageOperationStatus.OK) { @@ -113,45 +103,40 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { 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(), + 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)); + 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()); + AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), + additionalInfoParameterInfo.getKey()); result = Either.left(createdAI); return result; } - } finally { commitOrRollback(result); // unlock component graphLockOperation.unlockComponent(resourceId, nodeType); } - } /** @@ -162,13 +147,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { */ 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"); + BeEcompErrorManager.getInstance() + .logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string"); result = valueValidRes.right().value(); } else { String newValue = valueValidRes.left().value(); @@ -187,21 +171,18 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { * @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"); + BeEcompErrorManager.getInstance() + .logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string"); result = responseFormat; - } else { String convertedKey = validateKeyRes.left().value(); - if (log.isTraceEnabled() && key != null && !key.equals(convertedKey)) { log.trace("The additional information key {} was normalized to {}", key, convertedKey); } @@ -218,26 +199,29 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { * @param additionalInfoParameterInfo * @return response format in case the maximal number has been reached. */ - private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) { - + private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, + AdditionalInfoParameterInfo additionalInfoParameterInfo) { ResponseFormat result; - Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys(); - - Either checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true); + 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); + 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); + 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; } @@ -248,24 +232,20 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { * @return */ private Either validateValue(String value) { - boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value); if (!isNonEmptyString) { return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED)); } - boolean valid = StringValidator.getInstance().isValid(value, null); if (!valid) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value)); + 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; @@ -276,27 +256,31 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { /** * validate and normalize the key + * * @param key * @return Either */ private Either validateAndNormalizeKey(String key) { - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); additionalInfoParameterInfo.setKey(key); - String normKey = ValidationUtils.normalizeAdditionalInformation(key); boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(normKey); if (!isNonEmptyString) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label)); + return Either.right(componentsUtils + .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, + AdditionalInformationEnum.Label)); } boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(normKey); if (!isValidString) { if (!ValidationUtils.validateLength(normKey, 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_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, + AdditionalInformationEnum.Label)); } - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); + return Either.right(componentsUtils + .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, + null, AdditionalInformationEnum.Label)); } - return Either.left(normKey); } @@ -309,11 +293,11 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) { - + public Either updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, + AdditionalInfoParameterInfo additionalInfoParameterInfo, + String userId) { validateUserExists(userId); Either result = null; - ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); if (responseFormat != null) { result = Either.right(responseFormat); @@ -328,42 +312,39 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { 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(), + 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)); + 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()); + AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), + additionalInfoParameterInfo.getKey()); result = Either.left(parameterInfo); return result; } - } finally { commitOrRollback(result); // unlock component graphLockOperation.unlockComponent(resourceId, nodeType); } - } /** @@ -375,11 +356,11 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) { - + public Either deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, + AdditionalInfoParameterInfo additionalInfoParameterInfo, + String userId) { validateUserExists(userId); Either result = null; - ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); if (responseFormat != null) { return Either.right(responseFormat); @@ -392,41 +373,38 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } - try { - - Either findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); + 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)); + 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); - + 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)); + 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); } - } /** @@ -436,31 +414,26 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) { - + public Either getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, + AdditionalInfoParameterInfo additionalInfoParameterInfo, + String userId) { validateUserExists(userId); Either result = null; - try { - - Either findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); - + 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)); + result = Either.right(componentsUtils + .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); } - AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); - result = Either.left(foundAdditionalInfo); - return result; - } finally { commitOrRollback(result); } - } /** @@ -471,15 +444,13 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String userId) { - + public Either getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, + String userId) { validateUserExists(userId); - Either result = null; - try { - - Either findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false); + Either findIdRes = additionalInformationOperation + .getAllAdditionalInformationParameters(nodeType, resourceId, false); if (findIdRes.isRight()) { StorageOperationStatus status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findIdRes.right().value()); ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); @@ -488,39 +459,33 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { 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: + case Resource: + // verify that resource is checked-out and the user is the last - // 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: + // 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 - // 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()); + // 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/AnnotationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java index b0af789f28..f8d487169a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.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. @@ -17,9 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.openecomp.sdc.be.components.validation.AnnotationValidator; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.elements.Annotation; @@ -30,29 +36,19 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; - @Component public class AnnotationBusinessLogic { private final AnnotationTypeOperations annotationTypeOperations; - private final AnnotationValidator annotationValidator; - public AnnotationBusinessLogic(AnnotationTypeOperations annotationTypeOperations, - AnnotationValidator annotationValidator){ + public AnnotationBusinessLogic(AnnotationTypeOperations annotationTypeOperations, AnnotationValidator annotationValidator) { this.annotationTypeOperations = annotationTypeOperations; this.annotationValidator = annotationValidator; } public void validateAndMergeAnnotationsAndAssignToInput(Map inputs) { - if (!inputs.isEmpty()){ + if (!inputs.isEmpty()) { for (InputDefinition input : inputs.values()) { List inputAnnotationList = input.getAnnotations(); if (isNotEmpty(inputAnnotationList)) { @@ -72,11 +68,13 @@ public class AnnotationBusinessLogic { private void validateMergeAndSetAnnoProps(Annotation annotation, AnnotationTypeDefinition dbAnnotationTypeDefinition) { annotationValidator.validateAnnotationsProperties(annotation, dbAnnotationTypeDefinition); - List mergedPropertiesList = mergePropsOfAnnoDataTypeWithParsedAnnoProps(annotation.getProperties(), dbAnnotationTypeDefinition.getProperties()); + List mergedPropertiesList = mergePropsOfAnnoDataTypeWithParsedAnnoProps(annotation.getProperties(), + dbAnnotationTypeDefinition.getProperties()); annotation.setProperties(mergedPropertiesList); } - private List mergePropsOfAnnoDataTypeWithParsedAnnoProps(List annoProperties, List typePropertiesList) { + private List mergePropsOfAnnoDataTypeWithParsedAnnoProps(List annoProperties, + List typePropertiesList) { Set mergedPropertiesSet = new HashSet<>(typePropertiesList); Map typePropsMap = MapUtil.toMap(typePropertiesList, PropertyDefinition::getName); for (PropertyDataDefinition propertyDataDefinitionObject : annoProperties) { @@ -88,5 +86,4 @@ public class AnnotationBusinessLogic { } return new ArrayList<>(mergedPropertiesSet); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java index 15e9a77b15..34b01c7fd0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java @@ -21,8 +21,16 @@ */ package org.openecomp.sdc.be.components.impl; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.wrapWithTryCatch; + import com.google.common.annotations.VisibleForTesting; import fj.data.Either; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.validation.AccessValidations; @@ -44,108 +52,88 @@ import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.wrapWithTryCatch; - - @org.springframework.stereotype.Component public class ArchiveBusinessLogic { private static final Logger log = Logger.getLogger(ArchiveBusinessLogic.class.getName()); - private final JanusGraphDao janusGraphDao; private final AccessValidations accessValidations; private final ArchiveOperation archiveOperation; private final ToscaOperationFacade toscaOperationFacade; private final ComponentsUtils componentUtils; - private final CatalogOperation catalogOperations; + private final CatalogOperation catalogOperations; - public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils, - CatalogOperation catalogOperations) { + public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, + ToscaOperationFacade tof, ComponentsUtils componentsUtils, CatalogOperation catalogOperations) { this.janusGraphDao = janusGraphDao; this.accessValidations = accessValidations; this.archiveOperation = archiveOperation; this.toscaOperationFacade = tof; this.componentUtils = componentsUtils; - this.catalogOperations = catalogOperations; + this.catalogOperations = catalogOperations; } public void archiveComponent(String containerComponentType, String userId, String componentId) { User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_ARCHIVE"); Either, ActionStatus> result = this.archiveOperation.archiveComponent(componentId); - - if (result.isRight()){ + if (result.isRight()) { throw new ByActionStatusComponentException(result.right().value(), componentId); } this.auditAction(ArchiveOperation.Action.ARCHIVE, result.left().value(), user, containerComponentType); - // Send Archive Notification To Facade - wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.ARCHIVE)); + // Send Archive Notification To Facade + wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.ARCHIVE)); } public void restoreComponent(String containerComponentType, String userId, String componentId) { User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_RESTORE"); Either, ActionStatus> result = this.archiveOperation.restoreComponent(componentId); - if (result.isRight()){ + if (result.isRight()) { throw new ByActionStatusComponentException(result.right().value(), componentId); } this.auditAction(ArchiveOperation.Action.RESTORE, result.left().value(), user, containerComponentType); - // Send Archive Notification To Facade - wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.RESTORE)); + // Send Archive Notification To Facade + wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.RESTORE)); } - public List onVspArchive(String userId, List csarUuids){ + public List onVspArchive(String userId, List csarUuids) { return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.ARCHIVE); } - public List onVspRestore(String userId, List csarUuids){ + public List onVspRestore(String userId, List csarUuids) { return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.RESTORE); } private List onVspArchiveOrRestore(String userId, List csarUuids, ArchiveOperation.Action action) { - accessValidations.userIsAdminOrDesigner(userId, action.name() + "_VSP"); - ActionStatus actionStatus; List failedCsarIDs = new LinkedList<>(); - for (String csarUuid : csarUuids) { try { - if (action == ArchiveOperation.Action.ARCHIVE) { actionStatus = this.archiveOperation.onVspArchived(csarUuid); } else { actionStatus = this.archiveOperation.onVspRestored(csarUuid); } - //If not found VFs with this CSAR ID we still want a success (nothing is actually done) if (actionStatus == ActionStatus.RESOURCE_NOT_FOUND) { actionStatus = ActionStatus.OK; } - if (actionStatus != ActionStatus.OK) { failedCsarIDs.add(csarUuid); } - } catch (Exception e) { log.error("Failed to handle notification: {} on VSP for csarUuid: {}", action.name(), csarUuid); log.error("Exception Thrown:", e); failedCsarIDs.add(csarUuid); } } - return failedCsarIDs; } public Map> getArchiveComponents(String userId, List excludeTypes) { try { - - Either, StorageOperationStatus> components = toscaOperationFacade.getCatalogOrArchiveComponents(false, excludeTypes); + Either, StorageOperationStatus> components = toscaOperationFacade + .getCatalogOrArchiveComponents(false, excludeTypes); if (components.isLeft()) { List comps = components.left().value(); return comps.stream().collect(Collectors.groupingBy(cmpt -> ComponentTypeEnum.findParamByType(cmpt.getComponentType()))); @@ -153,52 +141,54 @@ public class ArchiveBusinessLogic { log.info("No components found"); return new HashMap(); } - } catch (Exception e){ + } catch (Exception e) { log.error("Error fetching archived elements", e); throw e; - } - finally { + } finally { janusGraphDao.commit(); } } - @VisibleForTesting void auditAction(ArchiveOperation.Action action, List affectedCompIds, User user, String containerComponentType) { String comment = String.format("All versions of this component were %s", action == ArchiveOperation.Action.ARCHIVE ? "archived" : "restored"); HashSet auditDoneUUIDs = new HashSet<>(); - for (String componentId : affectedCompIds){ + for (String componentId : affectedCompIds) { Either result = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView()); if (result.isRight()) { - log.error(EcompLoggerErrorCode.DATA_ERROR, null, "GetToscaElement", - result.right().value().name() + "for component with id {}", componentId); + log.error(EcompLoggerErrorCode.DATA_ERROR, null, "GetToscaElement", result.right().value().name() + "for component with id {}", + componentId); continue; } if (auditDoneUUIDs.add(result.left().value().getUUID())) { //a component with this UUID is not added to audit DB/log for current archive/restore operation yet - add to audit DB now - AuditingActionEnum auditAction = action == ArchiveOperation.Action.ARCHIVE ? AuditingActionEnum.ARCHIVE_COMPONENT : AuditingActionEnum.RESTORE_COMPONENT; //The audit Action - result.left().foreachDoEffect( - c -> { - // The archive/restore records have been retrieved from Cassandra using the separate queries. - // Setting current version as null allows to avoid appearing same records in ActivityLog twice: - // - first time as per current version query - //- second type as per archive/restore query - c.setVersion(null); - componentUtils.auditComponentAdmin(componentUtils.getResponseFormat(ActionStatus.OK), user, c, auditAction, ComponentTypeEnum.findByParamName(containerComponentType), comment); - }); + + AuditingActionEnum auditAction = action == ArchiveOperation.Action.ARCHIVE ? AuditingActionEnum.ARCHIVE_COMPONENT + : AuditingActionEnum.RESTORE_COMPONENT; //The audit Action + result.left().foreachDoEffect(c -> { + // The archive/restore records have been retrieved from Cassandra using the separate queries. + + // Setting current version as null allows to avoid appearing same records in ActivityLog twice: + + // - first time as per current version query + + //- second type as per archive/restore query + c.setVersion(null); + componentUtils.auditComponentAdmin(componentUtils.getResponseFormat(ActionStatus.OK), user, c, auditAction, + ComponentTypeEnum.findByParamName(containerComponentType), comment); + }); } } } - protected Either sendNotificationToFacade(String componentId, - ChangeTypeEnum changeStatus) { - log.debug("build {} notification for facade start", changeStatus.name()); - Either toscaElement = toscaOperationFacade.getToscaElement(componentId); - Component component = toscaElement.left() - .value(); - ActionStatus status = catalogOperations.updateCatalog(changeStatus, component); - if (status != ActionStatus.OK) { - return Either.right(componentUtils.getResponseFormat(status)); - } - return Either.left(component); - } + + protected Either sendNotificationToFacade(String componentId, ChangeTypeEnum changeStatus) { + log.debug("build {} notification for facade start", changeStatus.name()); + Either toscaElement = toscaOperationFacade.getToscaElement(componentId); + Component component = toscaElement.left().value(); + ActionStatus status = catalogOperations.updateCatalog(changeStatus, component); + if (status != ActionStatus.OK) { + return Either.right(componentUtils.getResponseFormat(status)); + } + return Either.left(component); + } } 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 66dce60641..19eda82281 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 @@ -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. @@ -17,18 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; -import org.apache.commons.collections.MapUtils; -import org.openecomp.sdc.be.components.ArtifactsResolver; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -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.InterfaceDefinition; -import org.openecomp.sdc.be.model.Service; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -37,6 +27,14 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.components.ArtifactsResolver; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.InterfaceDefinition; +import org.openecomp.sdc.be.model.Service; @org.springframework.stereotype.Component("artifact-resolver") public class ArtifactResolverImpl implements ArtifactsResolver { @@ -45,7 +43,6 @@ public class ArtifactResolverImpl implements ArtifactsResolver { public ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId) { List allComponentsArtifacts = getAllComponentsArtifacts(component, componentType); return findById(allComponentsArtifacts, artifactId); - } @Override @@ -55,29 +52,23 @@ public class ArtifactResolverImpl implements ArtifactsResolver { } private ArtifactDefinition findById(List artifacts, String artifactId) { - return artifacts.stream() - .filter(artifact -> artifact.getUniqueId().equals(artifactId)) - .findFirst().orElse(null); + return artifacts.stream().filter(artifact -> artifact.getUniqueId().equals(artifactId)).findFirst().orElse(null); } private List getAllComponentsArtifacts(Component component, ComponentTypeEnum componentType) { Map deploymentArtifacts = Optional.ofNullable(component.getDeploymentArtifacts()).orElse(Collections.emptyMap()); Map artifacts = Optional.ofNullable(component.getArtifacts()).orElse(Collections.emptyMap()); - Map interfaceArtifacts= Collections.emptyMap(); + Map interfaceArtifacts = Collections.emptyMap(); Map interfaces = component.getInterfaces(); if (MapUtils.isNotEmpty(interfaces)) { - interfaceArtifacts = interfaces.values().stream() - .flatMap(inte -> inte.getOperationsMap().values().stream()) - .map(operation -> operation.getImplementationArtifact()).filter(Objects::nonNull) - .collect(Collectors.toMap(artifactDefinition -> artifactDefinition.getUniqueId(), - artifactDefinition -> artifactDefinition, (a1, a2) -> a1)); + interfaceArtifacts = interfaces.values().stream().flatMap(inte -> inte.getOperationsMap().values().stream()) + .map(operation -> operation.getImplementationArtifact()).filter(Objects::nonNull).collect(Collectors + .toMap(artifactDefinition -> artifactDefinition.getUniqueId(), artifactDefinition -> artifactDefinition, (a1, a2) -> a1)); } - Map serviceApiArtifacts = Collections.emptyMap(); if (componentType == ComponentTypeEnum.SERVICE) { serviceApiArtifacts = Optional.ofNullable(((Service) component).getServiceApiArtifacts()).orElse(Collections.emptyMap()); } - return appendAllArtifacts(deploymentArtifacts, artifacts, interfaceArtifacts, serviceApiArtifacts); } @@ -93,5 +84,4 @@ public class ArtifactResolverImpl implements ArtifactsResolver { Arrays.stream(artifacts).forEach(a -> allArtifacts.addAll(a.values())); return allArtifacts; } - } 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 046ad22159..849e3c8bdb 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 @@ -19,7 +19,6 @@ * Modifications copyright (c) 2020 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.be.dao.api.ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE; @@ -143,6 +142,13 @@ import org.yaml.snakeyaml.Yaml; @org.springframework.stereotype.Component("artifactBusinessLogic") public class ArtifactsBusinessLogic extends BaseBusinessLogic { + + 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"; + public static final String ARTIFACT_ACTION_LOCK = "Artifact action - lock "; + public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. "; + public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}"; private static final String RESOURCE_INSTANCE = "resource instance"; private static final String ARTIFACT_TYPE_OTHER = "OTHER"; private static final String ARTIFACT_DESCRIPTION = "artifact description"; @@ -150,41 +156,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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 final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class.getName()); private static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. "; private static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact."; - public static final String ARTIFACT_ACTION_LOCK = "Artifact action - lock "; - public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. "; private static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. "; private static final String NULL_PARAMETER = "One of the function parameteres is null"; - public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}"; private static final String ROLLBACK = "all changes rollback"; private static final String COMMIT = "all changes committed"; private static final String UPDATE_ARTIFACT = "Update Artifact"; private static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}"; private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @javax.annotation.Resource private IInterfaceLifecycleOperation interfaceLifecycleOperation; @javax.annotation.Resource private UserAdminOperation userOperaton; - @javax.annotation.Resource private IElementOperation elementOperation; - @javax.annotation.Resource private IHeatParametersOperation heatParametersOperation; - private ArtifactCassandraDao artifactCassandraDao; private ToscaExportHandler toscaExportUtils; private CsarUtils csarUtils; @@ -194,13 +187,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private NodeTemplateOperation nodeTemplateOperation; @Autowired - public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils, - CsarUtils csarUtils, LifecycleBusinessLogic lifecycleBusinessLogic, UserBusinessLogic userBusinessLogic, + public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils, CsarUtils csarUtils, + LifecycleBusinessLogic lifecycleBusinessLogic, UserBusinessLogic userBusinessLogic, ArtifactsResolver artifactsResolver, IElementOperation elementDao, IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.artifactCassandraDao = artifactCassandraDao; this.toscaExportUtils = toscaExportUtils; this.csarUtils = csarUtils; @@ -209,20 +203,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { this.artifactsResolver = artifactsResolver; } - public enum ArtifactOperationEnum { - CREATE, UPDATE, DELETE, DOWNLOAD, LINK; + public static Either ifTrue(boolean predicate, Supplier> ifTrue) { + return predicate ? ifTrue.get() : Either.left(false); + } - public static boolean isCreateOrLink(ArtifactOperationEnum operation) { - return operation == CREATE || operation == LINK; - } + public static Either forEach(Either e, Consumer c) { + return e.left().map(l -> { + c.accept(l); + return l; + }); + } + + private static Option findFirstMatching(Component component, Predicate filter) { + return Option.ofOptional(component.getComponentInstances().stream().filter(filter).findFirst()); } // new flow US556184 public Either 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) { - + 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 @@ -233,13 +234,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } // step 3 - check user existence + // step 4 - check user's role User user = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction); validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation); - // steps 5 - 6 - 7 + // 5. check service/resource existence + // 6. check service/resource check out + // 7. user is owner of checkout state Component component = null; String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; @@ -249,45 +253,49 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { validateResourceInstanceById(component, componentId); } // step 8 - - return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, - originData, interfaceName, operationName, user, component, shouldLock, inTransaction, true); + return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, + operationName, user, component, shouldLock, inTransaction, true); } - public Either 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 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); } /** - * 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)} + * 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 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) { + public Either 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) { AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); - artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, - artifactUniqueId, artifactDefinition, auditingAction, user, - component, shouldLock, inTransaction); - + artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, + component, shouldLock, inTransaction); // step 10 Either result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, - origMd5, originData, interfaceName, operationName, auditingAction, user, component, shouldLock, inTransaction, needUpdateGroup); + origMd5, originData, interfaceName, operationName, auditingAction, user, component, shouldLock, inTransaction, needUpdateGroup); //TODO: audit positive action return result; } @VisibleForTesting - ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, - Component component, boolean shouldLock, boolean inTransaction) { + ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, + ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, Component component, + boolean shouldLock, boolean inTransaction) { ArtifactDefinition artifactInfoToReturn = artifactInfo; ArtifactOperationEnum operationEnum = operation.getArtifactOperationEnum(); - if (operationEnum == ArtifactOperationEnum.UPDATE || operationEnum == ArtifactOperationEnum.DELETE || operationEnum == ArtifactOperationEnum.DOWNLOAD) { + if (operationEnum == ArtifactOperationEnum.UPDATE || operationEnum == ArtifactOperationEnum.DELETE + || operationEnum == ArtifactOperationEnum.DOWNLOAD) { ArtifactDefinition dbArtifact = getArtifactIfBelongsToComponent(componentId, componentType, artifactId, component); if (operation.isDownload()) { artifactInfoToReturn = dbArtifact; @@ -300,28 +308,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { @VisibleForTesting void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, Component component, ArtifactDefinition artifactDefinition, boolean shouldLock, boolean inTransaction) { - - if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) - && ComponentTypeEnum.SERVICE == component.getComponentType()) { - ComponentInstance componentInstance = component.getComponentInstances() - .stream() - .filter(p -> p.getUniqueId().equals(componentId)) - .findAny() - .orElse(null); + if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) && ComponentTypeEnum.SERVICE == component + .getComponentType()) { + ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)) + .findAny().orElse(null); if (componentInstance == null) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentId, - "instance", "Service", component.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentId, "instance", "Service", + component.getName()); } Map deploymentArtifacts = componentInstance.getDeploymentArtifacts(); - - ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values() - .stream() - .filter(p -> p.getUniqueId() - .equals(artifactDefinition.getUniqueId())) - .findAny() - .orElse(null); - Either eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, - componentType, component, componentInstance.getName(), user, componentId, shouldLock, inTransaction); + ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream() + .filter(p -> p.getUniqueId().equals(artifactDefinition.getUniqueId())).findAny().orElse(null); + Either eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, + componentInstance.getName(), user, componentId, shouldLock, inTransaction); if (eitherGenerated.isRight()) { throw new ByResponseFormatComponentException((eitherGenerated.right().value())); } @@ -330,72 +329,62 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private boolean artifactGenerationRequired(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))); + 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 generateAndSaveToscaArtifact( - ArtifactDefinition artifactDefinition, Component component, - User user, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction, - boolean fetchTemplatesFromDB) { - - return decodeToscaArtifactPayload( - component, isInCertificationRequest, fetchTemplatesFromDB, artifactDefinition.getArtifactType() - ).left().bind(payload -> { - // TODO: Avoid output argument - artifactDefinition.setPayload(payload); - artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(payload)); - return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, - AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), - user, component.getComponentType(), component, payload, shouldLock, inTransaction - ); - }).right().map(ex -> { - // TODO: This should not be done but in order to keep this refactoring small enough, we stop here. - // Bubble up this exception - throw ex; - }); + return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType() + .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum()); + } + + public Either generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, Component component, User user, + boolean isInCertificationRequest, boolean shouldLock, + boolean inTransaction, boolean fetchTemplatesFromDB) { + return decodeToscaArtifactPayload(component, isInCertificationRequest, fetchTemplatesFromDB, artifactDefinition.getArtifactType()).left() + .bind(payload -> { + // TODO: Avoid output argument + artifactDefinition.setPayload(payload); + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(payload)); + return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, + artifactDefinition.getUniqueId(), user, component.getComponentType(), component, payload, shouldLock, inTransaction); + }).right().map(ex -> { + // TODO: This should not be done but in order to keep this refactoring small enough, we stop here. + + // Bubble up this exception + throw ex; + }); } - private Either decodeToscaArtifactPayload( - Component parent, - boolean isInCertificationRequest, - boolean fetchTemplatesFromDB, - String artifactType - ) { + private Either decodeToscaArtifactPayload(Component parent, boolean isInCertificationRequest, + boolean fetchTemplatesFromDB, String artifactType) { log.debug("tosca artifact generation"); if (ArtifactTypeEnum.TOSCA_CSAR.getType().equals(artifactType)) { - return csarUtils - .createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest) - .right().map(error -> { - log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error); - return new ByResponseFormatComponentException(error); - }); + return csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest).right().map(error -> { + log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error); + return new ByResponseFormatComponentException(error); + }); } else { - return toscaExportUtils - .exportComponent(parent) - .left().map(toscaRepresentation -> { - log.debug("Tosca yaml exported for component {} ", parent.getUniqueId()); - return toscaRepresentation.getMainYaml(); - }).right().map(toscaError -> { - log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError); - return new ByActionStatusComponentException(componentsUtils.convertFromToscaError(toscaError)); - }); + return toscaExportUtils.exportComponent(parent).left().map(toscaRepresentation -> { + log.debug("Tosca yaml exported for component {} ", parent.getUniqueId()); + return toscaRepresentation.getMainYaml(); + }).right().map(toscaError -> { + log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError); + return new ByActionStatusComponentException(componentsUtils.convertFromToscaError(toscaError)); + }); } } - private Either doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, - String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { + private Either doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, + String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData, + String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, + Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { if (interfaceName != null && operationName != null) { interfaceName = interfaceName.toLowerCase(); operationName = operationName.toLowerCase(); @@ -418,23 +407,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, parent)); break; case UPDATE: - result = handleUpdate(componentId, componentType, operation, artifactId, artifactInfo, null, origMd5, originData, interfaceName, operationName, - auditingAction, user, parent, needUpdateGroup); + result = handleUpdate(componentId, componentType, operation, artifactId, artifactInfo, null, origMd5, originData, interfaceName, + operationName, auditingAction, user, parent, needUpdateGroup); break; case CREATE: - result = handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, - operationName); + result = handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, + interfaceName, operationName); break; case LINK: result = Either.left(handleLink(componentId, artifactInfo, componentType, parent)); break; default: - throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum()); + throw new UnsupportedOperationException( + "In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum()); } operationSucceeded = true; return result; - } - finally { + } finally { handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded); } } @@ -442,44 +431,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private void lockComponent(ComponentTypeEnum componentType, String artifactId, AuditingActionEnum auditingAction, User user, Component parent) { try { lockComponent(parent, ARTIFACT_ACTION_LOCK); - }catch (ComponentException e){ - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, null, null, artifactId, e.getResponseFormat(), - componentType, null); + } catch (ComponentException e) { + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, null, null, artifactId, e.getResponseFormat(), componentType, null); throw e; } } @VisibleForTesting - public Either handleUpdate(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, - ArtifactDefinition artifactInfo, byte[] decodedPayload, String origMd5, String originData, String interfaceName, - String operationName, AuditingActionEnum auditingAction, User user, Component parent, - boolean needUpdateGroup) { + public Either handleUpdate(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, + String artifactId, ArtifactDefinition artifactInfo, byte[] decodedPayload, + String origMd5, String originData, String interfaceName, String operationName, + AuditingActionEnum auditingAction, User user, Component parent, + boolean needUpdateGroup) { Either result; validateArtifactType(artifactInfo); final String artifactType = artifactInfo.getArtifactType(); - if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && - (ArtifactTypeEnum.HEAT.getType().equals(artifactType) || - ArtifactTypeEnum.HEAT_VOL.getType().equals(artifactType) || - ArtifactTypeEnum.HEAT_NET.getType().equals(artifactType) || - ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType))) { - result = handleUpdateHeatEnvAndHeatMeta(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation); + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && (ArtifactTypeEnum.HEAT.getType().equals(artifactType) || ArtifactTypeEnum.HEAT_VOL + .getType().equals(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equals(artifactType) || ArtifactTypeEnum.HEAT_ENV.getType() + .equals(artifactType))) { + result = handleUpdateHeatEnvAndHeatMeta(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, + origMd5, operation); if (needUpdateGroup) { ActionStatus error = updateGroupInstance(artifactInfo, result.left().value(), parent, componentId); if (error != ActionStatus.OK) { throw new ByActionStatusComponentException(error); } } - } - else if (componentType == ComponentTypeEnum.RESOURCE && ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType)) { - result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, componentType, parent, originData, origMd5, operation, needUpdateGroup); - } - else { + } else if (componentType == ComponentTypeEnum.RESOURCE && ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType)) { + result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, componentType, parent, originData, origMd5, + operation, needUpdateGroup); + } else { if (decodedPayload == null) { - decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, - componentType, parent, origMd5, originData, interfaceName, operationName); + decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, + originData, interfaceName, operationName); } - result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction - ); + result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction); if (needUpdateGroup && result.isLeft()) { ArtifactDefinition updatedArtifact = result.left().value(); updateGroupForHeat(artifactInfo, updatedArtifact, parent); @@ -494,30 +480,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private void validateArtifactType(final ArtifactDefinition artifactInfo, - final ComponentTypeEnum componentType) { - final ArtifactConfiguration artifactConfiguration = - loadArtifactTypeConfig(artifactInfo.getArtifactType()).orElse(null); + private void validateArtifactType(final ArtifactDefinition artifactInfo, final ComponentTypeEnum componentType) { + final ArtifactConfiguration artifactConfiguration = loadArtifactTypeConfig(artifactInfo.getArtifactType()).orElse(null); if (artifactConfiguration == null) { - BeEcompErrorManager.getInstance() - .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); + BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName()); final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE); throw new ByResponseFormatComponentException(responseFormat); } - final ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType(); try { validateArtifactType(componentType, artifactGroupType, artifactConfiguration); } catch (final ComponentException e) { log.debug("Artifact is invalid", e); BeEcompErrorManager.getInstance() - .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo - .getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); + .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), + "Artifact " + artifactInfo.getArtifactName()); log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType()); final ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo - .getArtifactType()); + .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); throw new ByResponseFormatComponentException(responseFormat); } } @@ -525,22 +506,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private void validateArtifactType(final ComponentTypeEnum componentType, final ArtifactGroupTypeEnum groupType, final ArtifactConfiguration artifactConfiguration) { final boolean supportComponentType = - CollectionUtils.isNotEmpty(artifactConfiguration.getComponentTypes()) && - artifactConfiguration.getComponentTypes().stream() - .anyMatch(componentType1 -> componentType1.getValue().equalsIgnoreCase(componentType.getValue())); + CollectionUtils.isNotEmpty(artifactConfiguration.getComponentTypes()) && artifactConfiguration.getComponentTypes().stream() + .anyMatch(componentType1 -> componentType1.getValue().equalsIgnoreCase(componentType.getValue())); if (!supportComponentType) { - log.debug("Artifact Type '{}' not supported for Component Type '{}'", - artifactConfiguration.getType(), componentType.getValue()); - throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, - artifactConfiguration.getType()); + log.debug("Artifact Type '{}' not supported for Component Type '{}'", artifactConfiguration.getType(), componentType.getValue()); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactConfiguration.getType()); } - final boolean supportResourceType = artifactConfiguration.hasSupport(groupType); if (!supportResourceType) { - log.debug("Artifact Type '{}' not supported for Component Type '{}' and Category '{}'", - artifactConfiguration.getType(), componentType.getValue(), groupType.getType()); - throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, - artifactConfiguration.getType()); + log.debug("Artifact Type '{}' not supported for Component Type '{}' and Category '{}'", artifactConfiguration.getType(), + componentType.getValue(), groupType.getType()); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactConfiguration.getType()); } } @@ -550,8 +526,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (CollectionUtils.isEmpty(artifactConfigurationList)) { return false; } - return artifactConfigurationList.stream() - .anyMatch(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType)); + return artifactConfigurationList.stream().anyMatch(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType)); } @VisibleForTesting @@ -559,17 +534,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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()); + .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()); - if(!artifactInfo.getArtifactUUID().equals(artAfterUpdate.getArtifactUUID())){ + if (!artifactInfo.getArtifactUUID().equals(artAfterUpdate.getArtifactUUID())) { g.setGroupUUID(UniqueIdBuilder.generateUUID()); } }); @@ -584,14 +556,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } @VisibleForTesting - ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent) { + ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, + ArtifactDefinition artHEAfterUpdate, Component parent) { 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()); + .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()); @@ -614,10 +584,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, String parentId) { List updatedGroupInstances = new ArrayList<>(); List groupInstances = null; - Optional componentInstOp = parent.getComponentInstances() - .stream() - .filter(ci -> ci.getUniqueId().equals(parentId)) - .findFirst(); + Optional componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)) + .findFirst(); if (componentInstOp.isPresent()) { groupInstances = componentInstOp.get().getGroupInstances(); } @@ -626,15 +594,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { for (GroupInstance groupInstance : groupInstances) { isUpdated = false; if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts() - .contains(artifactInfo - .getUniqueId())) { + .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())) { + .contains(artifactInfo.getArtifactUUID())) { groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID()); groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID()); isUpdated = true; @@ -644,7 +610,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } } - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances); + Either, StorageOperationStatus> status = toscaOperationFacade + .updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances); if (status.isRight()) { log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId()); return componentsUtils.convertFromStorageResponse(status.right().value()); @@ -654,17 +621,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ArtifactDefinition generateNotSavedArtifact(Component parent, ArtifactDefinition artifactDefinition) { if (artifactDefinition.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) { - Either decodedPayload = decodeToscaArtifactPayload(parent, false, - false, artifactDefinition.getArtifactType()); + Either decodedPayload = decodeToscaArtifactPayload(parent, false, false, + artifactDefinition.getArtifactType()); // TODO: This should not be done, but in order to keep this refactoring relatively small, we stop here - if(decodedPayload.isRight()) + if (decodedPayload.isRight()) { throw decodedPayload.right().value(); - else { + } else { artifactDefinition.setPayload(decodedPayload.left().value()); return artifactDefinition; } - } - else { + } else { String heatArtifactId = artifactDefinition.getGeneratedFromId(); Either heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId); if (heatRes.isRight()) { @@ -677,11 +643,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private Either handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, - ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, - boolean needToUpdateGroup) { - Either artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo - .getGeneratedFromId()); + private Either handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, + AuditingActionEnum auditingAction, + ComponentTypeEnum componentType, Component parent, + String originData, String origMd5, + ArtifactOperationInfo operation, boolean needToUpdateGroup) { + Either artifactHeatRes = artifactToscaOperation + .getArtifactById(componentId, artifactInfo.getGeneratedFromId()); ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value(); if (origMd5 != null) { validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); @@ -703,7 +671,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } else { log.debug(ROLLBACK); if (!inTransaction) { - janusGraphDao.rollback(); + janusGraphDao.rollback(); } } if (shouldLock) { @@ -714,10 +682,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public ImmutablePair 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()); + log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value()); throw new ByResponseFormatComponentException(generated.right().value()); } return new ImmutablePair<>(csarArtifact.getArtifactName(), generated.left().value()); @@ -725,47 +691,54 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return downloadArtifact(csarArtifact); } - public ImmutablePair handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) { + public ImmutablePair handleDownloadRequestById(String componentId, String artifactId, String userId, + ComponentTypeEnum componentType, String parentId, String containerComponentType) { // perform all validation in common flow - Either result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null, - null, parentId, containerComponentType); + Either result = handleArtifactRequest(componentId, userId, componentType, + new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null, null, parentId, + containerComponentType); ArtifactDefinition artifactDefinition; Either insideValue = result; if (insideValue.isLeft()) { artifactDefinition = insideValue.left().value(); - } - else { + } 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 (new ImmutablePair<>(artifactDefinition.getArtifactName(), artifactDefinition - .getPayloadData())); + return (new ImmutablePair<>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData())); } return downloadArtifact(artifactDefinition); } - public Map handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) { + public Map handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, + String componentId, String artifactGroupType, String userId) { // step 1 + // detect auditing type Map resMap = null; - new Wrapper<>(); // step 2 + // check header if (userId == null) { log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId); throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } // step 3 + // check user existence + // step 4 - // check user's role + // check user's role validateUserExists(userId); // steps 5 - 6 - 7 + // 5. check service/resource existence + // 6. check service/resource check out + // 7. user is owner of checkout state String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; ComponentParametersView componentFilter = new ComponentParametersView(); @@ -774,14 +747,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { componentFilter.setIgnoreComponentInstances(false); } - - Component component = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum - .findByParamName(containerComponentType), componentFilter); + Component component = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), + componentFilter); lockComponent(component, ARTIFACT_ACTION_LOCK); boolean failed = false; try { ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType); - if (groupType == null) { log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId); throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); @@ -790,30 +761,26 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { List list = getDeploymentArtifacts(component, componentId); if (list != null && !list.isEmpty()) { resMap = list.stream().collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, Function.identity())); - } - else { + } else { resMap = new HashMap<>(); } return resMap; } else { - - Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType - .getNodeType(), groupType, componentId); + Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, + componentType.getNodeType(), groupType, componentId); if (artifactsMapStatus.isRight()) { if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId); throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); - } - else { + } else { resMap = new HashMap<>(); } - } - else { + } else { resMap = artifactsMapStatus.left().value(); } return resMap; } - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; } finally { @@ -821,23 +788,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (failed) { log.debug(ROLLBACK); janusGraphDao.rollback(); - } - else { + } else { log.debug(COMMIT); janusGraphDao.commit(); } - componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); } - } - private ArtifactDefinition getArtifactIfBelongsToComponent(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) { + private ArtifactDefinition getArtifactIfBelongsToComponent(String componentId, ComponentTypeEnum componentType, String artifactId, + Component component) { // check artifact existence - Either artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, - componentType, component.getUniqueId()); + Either artifactResult = artifactToscaOperation + .getArtifactById(componentId, artifactId, componentType, component.getUniqueId()); if (artifactResult.isRight()) { throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, artifactId, componentId); } @@ -860,22 +825,24 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return artifactResult.left().value(); } - private Either handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, - Component parent, String origMd5, String originData, String interfaceType, String operationName) { - byte[] decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, null, user, componentType, parent, origMd5, originData, interfaceType, operationName); + private Either handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, + AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, + Component parent, String origMd5, String originData, String interfaceType, + String operationName) { + byte[] decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, null, user, componentType, parent, origMd5, + originData, interfaceType, operationName); return createArtifact(parent, componentId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceType, operationName); } - private ArtifactDefinition handleLink(String componentId, ArtifactDefinition artifactInfo, ComponentTypeEnum componentType, - Component parent) { + private ArtifactDefinition handleLink(String componentId, ArtifactDefinition artifactInfo, ComponentTypeEnum componentType, Component parent) { ComponentInstance foundInstance = findComponentInstance(componentId, parent); String instanceId = null; if (foundInstance != null) { instanceId = foundInstance.getUniqueId(); } NodeTypeEnum nodeType = convertParentType(componentType); - Either artifactDefinitionEither = artifactToscaOperation.addArtifactToComponent(artifactInfo, parent, - nodeType, true, instanceId); + Either artifactDefinitionEither = artifactToscaOperation + .addArtifactToComponent(artifactInfo, parent, nodeType, true, instanceId); if (artifactDefinitionEither.isRight()) { throw new StorageException(artifactDefinitionEither.right().value(), artifactInfo.getArtifactDisplayName()); } @@ -885,55 +852,52 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return artifactDefinitionEither.left().value(); } - private Either lockComponentAndUpdateArtifact( - String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, - User user, ComponentTypeEnum componentType, Component parent, byte[] decodedPayload, - boolean shouldLock, boolean inTransaction) { - + private Either lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, + AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, Component parent, byte[] decodedPayload, + boolean shouldLock, boolean inTransaction) { boolean failed = false; boolean writeAudit = true; try { lockComponent(parent, shouldLock, ARTIFACT_ACTION_LOCK); writeAudit = false; - return updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType, - auditingAction); - } - catch (ComponentException ce) { - if(writeAudit) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(), - componentType, null); + return updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction); + } catch (ComponentException ce) { + if (writeAudit) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(), componentType, null); } failed = true; throw ce; - } - catch (StorageException se) { + } catch (StorageException se) { //TODO: audit failed = true; throw se; - } - finally { + } finally { if (shouldLock) { unlockComponent(failed, parent, inTransaction); } } } - private byte[] 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) { + private byte[] 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) { validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - return getValidPayload(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, interfaceType, operationName); + return getValidPayload(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, interfaceType, + operationName); } - private byte[] getValidPayload(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, - String artifactId, User user, ComponentTypeEnum componentType, Component parent, String interfaceType, String operationName) { + private byte[] getValidPayload(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, + AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, Component parent, + String interfaceType, String operationName) { // step 11 - Either validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent); + 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); throw new ByResponseFormatComponentException(responseFormat); } - Either payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); if (payloadEither.isRight()) { ResponseFormat responseFormat = payloadEither.right().value(); @@ -942,9 +906,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { throw new ByResponseFormatComponentException(responseFormat); } // validate heat parameters. this part must be after the parameters are + // extracted in "handlePayload" - Either validateAndConvertHeatParameters = validateAndConvertHeatParameters(artifactInfo, artifactInfo - .getArtifactType()); + Either validateAndConvertHeatParameters = validateAndConvertHeatParameters(artifactInfo, + artifactInfo.getArtifactType()); if (validateAndConvertHeatParameters.isRight()) { ResponseFormat responseFormat = validateAndConvertHeatParameters.right().value(); handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null); @@ -957,19 +922,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { - if (componentsUtils.isExternalApiEvent(auditingActionEnum)) { return; } - if (user == null) { user = new User(); user.setUserId("UNKNOWN"); } - handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName); + handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, + responseFormat, componentTypeEnum, resourceInstanceName); } - private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { + private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, + ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, + ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { switch (componentTypeEnum) { case RESOURCE: Resource resource = (Resource) component; @@ -979,11 +945,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { resource.setName(componentId); } componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum, - ResourceVersionInfo.newBuilder() - .artifactUuid(prevArtifactUuid) - .build(), currentArtifactUuid, artifactDefinition); + ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(), currentArtifactUuid, artifactDefinition); break; - case SERVICE: Service service = (Service) component; if (service == null) { @@ -991,29 +954,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { service = new Service(); service.setName(componentId); } - componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()), - ResourceVersionInfo.newBuilder() - .artifactUuid(prevArtifactUuid) - .build(), - ResourceVersionInfo.newBuilder() - .artifactUuid(currentArtifactUuid) - .build(), - null, artifactDefinition, null); + componentsUtils + .auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()), + ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(), + ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).build(), null, artifactDefinition, null); break; - case RESOURCE_INSTANCE: if (resourceInstanceName == null) { resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId); } componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, - new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()), - ResourceVersionInfo.newBuilder() - .artifactUuid(prevArtifactUuid) - .build(), - ResourceVersionInfo.newBuilder() - .artifactUuid(currentArtifactUuid) - .build(), - null, artifactDefinition, null); + new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()), + ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(), + ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).build(), null, artifactDefinition, null); break; default: break; @@ -1021,11 +974,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private String getResourceInstanceNameFromComponent(Component component, String componentId) { - ComponentInstance resourceInstance = component.getComponentInstances() - .stream() - .filter(p -> p.getUniqueId().equals(componentId)) - .findFirst() - .orElse(null); + ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst() + .orElse(null); String resourceInstanceName = null; if (resourceInstance != null) { resourceInstanceName = resourceInstance.getName(); @@ -1053,19 +1003,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private Either validateInput(final String componentId, - final ArtifactDefinition artifactInfo, - final ArtifactOperationInfo operation, - final String artifactId, final User user, - String interfaceName, - String operationName, - final ComponentTypeEnum componentType, - final Component parentComponent) { - - final ArtifactDefinition existingArtifactInfo = - findArtifact(parentComponent, componentType, componentId, operation, artifactId); - final boolean isCreateOrLinkOperation = - ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()); + private Either validateInput(final String componentId, final ArtifactDefinition artifactInfo, + final ArtifactOperationInfo operation, final String artifactId, final User user, + String interfaceName, String operationName, + final ComponentTypeEnum componentType, final Component parentComponent) { + final ArtifactDefinition existingArtifactInfo = findArtifact(parentComponent, componentType, componentId, operation, artifactId); + final boolean isCreateOrLinkOperation = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()); if (!isCreateOrLinkOperation && existingArtifactInfo == null) { throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactId); } @@ -1094,13 +1037,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { operationName = operationName.toLowerCase(); interfaceName = interfaceName.toLowerCase(); } - Either logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType); + 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 + // through other artifacts flow final ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL; if (operation.isNotCreateOrLink()) { @@ -1108,7 +1052,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } else { checkCreateFields(user, artifactInfo, artifactGroupType); } - composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName); if (existingArtifactInfo != null) { artifactInfo.setMandatory(existingArtifactInfo.getMandatory()); @@ -1116,7 +1059,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { validateArtifactTypeNotChanged(artifactInfo, existingArtifactInfo); } } - // artifactGroupType is not allowed to be updated if (operation.isNotCreateOrLink()) { Either validateGroupType = validateOrSetArtifactGroupType(artifactInfo, existingArtifactInfo); @@ -1124,7 +1066,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(validateGroupType.right().value()); } } - setArtifactTimeout(artifactInfo, existingArtifactInfo); if (isHeatArtifact(artifactInfo)) { validateHeatArtifact(parentComponent, componentId, artifactInfo); @@ -1132,34 +1073,26 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (isDeploymentArtifact(artifactInfo)) { if (componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { final String artifactName = artifactInfo.getArtifactName(); - final String existingArtifactName = - (existingArtifactInfo == null) ? null : existingArtifactInfo.getArtifactName(); - - if (operation.isCreateOrLink() - || ((artifactName != null) && !artifactName.equalsIgnoreCase(existingArtifactName))) { + final String existingArtifactName = (existingArtifactInfo == null) ? null : existingArtifactInfo.getArtifactName(); + if (operation.isCreateOrLink() || ((artifactName != null) && !artifactName.equalsIgnoreCase(existingArtifactName))) { validateSingleDeploymentArtifactName(artifactName, parentComponent); } } validateDeploymentArtifact(artifactInfo, component); } - Either descriptionResult = validateAndCleanDescription(artifactInfo); if (descriptionResult.isRight()) { return Either.right(descriptionResult.right().value()); } - validateArtifactType(artifactInfo, component.getComponentType()); artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase()); if (existingArtifactInfo != null && existingArtifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.SERVICE_API) { // 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, existingArtifactInfo); if (validateUpdate.isRight()) { log.debug("serviceApi first update cnnot be without payload."); @@ -1170,13 +1103,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setApiUrl(null); log.error("Artifact URL cannot be set through this API - ignoring"); } - if (Boolean.TRUE.equals(artifactInfo.getServiceApi())) { artifactInfo.setServiceApi(false); log.error("Artifact service API flag cannot be changed - ignoring"); } } - return Either.left(artifactInfo); } @@ -1186,12 +1117,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Component '{}' not found ", componentId); throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, componentId); } - return component.left().value(); } - private void ignoreUnupdateableFieldsInUpdate(final ArtifactOperationInfo operation, - final ArtifactDefinition artifactInfo, + private void ignoreUnupdateableFieldsInUpdate(final ArtifactOperationInfo operation, final ArtifactDefinition artifactInfo, final ArtifactDefinition currentArtifactInfo) { if (operation.isUpdate()) { artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType()); @@ -1200,9 +1129,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private ArtifactDefinition findArtifact(final Component parentComponent, final ComponentTypeEnum componentType, - final String parentId, final ArtifactOperationInfo operation, - final String artifactId) { + private ArtifactDefinition findArtifact(final Component parentComponent, final ComponentTypeEnum componentType, final String parentId, + final ArtifactOperationInfo operation, final String artifactId) { ArtifactDefinition foundArtifact = null; if (StringUtils.isNotEmpty(artifactId)) { foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); @@ -1222,8 +1150,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ArtifactDefinition foundArtifact; if (parentComponent.getUniqueId().equals(parentId)) { foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId); - } - else { + } else { ComponentInstance instance = findComponentInstance(parentId, parentComponent); foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId); } @@ -1242,10 +1169,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactType); } validateArtifactType(parentComponentType, artifactInfo.getArtifactGroupType(), artifactConfiguration); - - if (component.getComponentType() == ComponentTypeEnum.RESOURCE || - component.getComponentType() == ComponentTypeEnum.RESOURCE_INSTANCE) { - + if (component.getComponentType() == ComponentTypeEnum.RESOURCE || component.getComponentType() == ComponentTypeEnum.RESOURCE_INSTANCE) { final ResourceTypeEnum resourceType = ((Resource) component).getResourceType(); validateResourceType(resourceType, artifactInfo, artifactConfiguration.getResourceTypes()); } @@ -1255,89 +1179,70 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) { if (componentType == ComponentTypeEnum.RESOURCE) { return NodeTypeEnum.Resource; - } - else if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + } else if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { return NodeTypeEnum.ResourceInstance; - } - else { + } else { return NodeTypeEnum.Service; } } // This method is here for backward compatibility - when other parts of the code are cleaned can change to use the internal version - public Either handleDelete( - String parentId, String artifactId, User user, Component parent, - boolean shouldLock, boolean inTransaction) { - + public Either handleDelete(String parentId, String artifactId, User user, Component parent, + boolean shouldLock, boolean inTransaction) { ResponseFormat responseFormat; boolean operationSucceeded = false; if (shouldLock) { lockComponent(ComponentTypeEnum.RESOURCE, artifactId, AuditingActionEnum.ARTIFACT_DELETE, user, parent); } try { - ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId, - ComponentTypeEnum.RESOURCE, parent); + ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId, ComponentTypeEnum.RESOURCE, parent); operationSucceeded = true; return Either.left(artifactDefinition); - } - catch (ComponentException ce) { + } catch (ComponentException ce) { responseFormat = componentsUtils.getResponseFormat(ce); - handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null, - artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null); + handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null, artifactId, responseFormat, + ComponentTypeEnum.RESOURCE, null); return Either.right(responseFormat); - } - catch (StorageException se) { + } catch (StorageException se) { responseFormat = componentsUtils.getResponseFormat(se); - handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null, - artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null); + handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null, artifactId, responseFormat, + ComponentTypeEnum.RESOURCE, null); return Either.right(responseFormat); } finally { handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded); } } - private ArtifactDefinition handleDeleteInternal( - String parentId, String artifactId, - ComponentTypeEnum componentType, Component parent - ) { + private ArtifactDefinition handleDeleteInternal(String parentId, String artifactId, ComponentTypeEnum componentType, Component parent) { NodeTypeEnum parentType = convertParentType(componentType); log.debug("Going to find the artifact {} on the component {}", artifactId, parent.getUniqueId()); - - Either, ActionStatus> getArtifactRes = - findArtifact(artifactId, parent, parentId, componentType); + Either, ActionStatus> getArtifactRes = findArtifact(artifactId, parent, parentId, + componentType); if (getArtifactRes.isRight()) { - log.debug("Failed to find the artifact {} belonging to {} on the component {}", - artifactId, parentId, parent.getUniqueId()); + log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, parent.getUniqueId()); throw new ByActionStatusComponentException(getArtifactRes.right().value(), artifactId); } ArtifactDefinition foundArtifact = getArtifactRes.left().value().getLeft(); ComponentInstance foundInstance = getArtifactRes.left().value().getRight(); - String esId = foundArtifact.getEsId(); - Either needClone = ifTrue(StringUtils.isNotEmpty(esId), () -> forEach( - artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType), - b -> log.debug("handleDelete: clone is needed for deleting {} held by {} in component {} {}? {}", - foundArtifact.getArtifactName(), parentType, parent.getUniqueId(), parent.getName(), b) - )); - + Either needClone = ifTrue(StringUtils.isNotEmpty(esId), + () -> forEach(artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType), b -> log + .debug("handleDelete: clone is needed for deleting {} held by {} in component {} {}? {}", foundArtifact.getArtifactName(), parentType, + parent.getUniqueId(), parent.getName(), b))); boolean needToClone = false; // TODO: This should not be done, but in order to keep this refactoring small, we stop here. + // Remove this block once the above refactoring is merged. - if(needClone.isLeft()) { + if (needClone.isLeft()) { needToClone = needClone.left().value(); } else { throw new StorageException(needClone.right().value(), foundArtifact.getArtifactDisplayName()); } - boolean isNeedToDeleteArtifactFromDB = - componentType == ComponentTypeEnum.RESOURCE_INSTANCE && - isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId); - + componentType == ComponentTypeEnum.RESOURCE_INSTANCE && isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId); boolean isDuplicated = false; - ArtifactDataDefinition updatedArtifact = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needToClone); isDuplicated = updatedArtifact.getDuplicated(); - if (!needToClone && !isDuplicated && isNeedToDeleteArtifactFromDB) { log.debug("Going to delete the artifact {} from the database. ", artifactId); CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId); @@ -1349,7 +1254,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { List updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, foundInstance.getGroupInstances()); if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances); + Either, StorageOperationStatus> status = toscaOperationFacade + .updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances); if (status.isRight()) { log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId()); throw new StorageException(status.right().value(), foundArtifact.getArtifactDisplayName()); @@ -1373,17 +1279,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return foundArtifact; } - public static Either ifTrue(boolean predicate, Supplier> ifTrue) { - return predicate ? ifTrue.get() : Either.left(false); - } - - public static Either forEach(Either e, Consumer c) { - return e.left().map(l -> { - c.accept(l); - return l; - }); - } - private boolean isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) { Optional componentInstanceOpt = parent.getComponentInstanceById(instanceId); if (!componentInstanceOpt.isPresent()) { @@ -1399,20 +1294,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Component origComponent = getContainerRes.left().value(); Map deploymentArtifacts = origComponent.getDeploymentArtifacts(); if (MapUtils.isNotEmpty(deploymentArtifacts)) { - Optional op = deploymentArtifacts.keySet() - .stream() - .filter(a -> a.equals(foundArtifact.getArtifactLabel())) - .findAny(); + Optional op = deploymentArtifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny(); if (op.isPresent()) { return false; } } Map artifacts = origComponent.getArtifacts(); if (MapUtils.isNotEmpty(artifacts)) { - Optional op = artifacts.keySet() - .stream() - .filter(a -> a.equals(foundArtifact.getArtifactLabel())) - .findAny(); + Optional op = artifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny(); if (op.isPresent()) { return false; } @@ -1430,8 +1319,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { group.getArtifacts().remove(artifactId); isUpdated = true; } - if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid() - .contains(foundArtifact.getArtifactUUID())) { + if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID()); isUpdated = true; } @@ -1443,29 +1331,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return updatedGroups; } - private List getUpdatedGroupInstances( - String artifactId, ArtifactDefinition foundArtifact, List groupInstances - ) { + private List getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List groupInstances) { if (CollectionUtils.isEmpty(groupInstances)) { return new ArrayList<>(); } // TODO: A defensive copy should be created here for groupInstances. Modifying + // arguments (aka output arguments) is overall a bad practice as explained in + // Clean Code by Robert Martin. - // A better approach would be to use Lenses. + // A better approach would be to use Lenses. return groupInstances.stream().filter(gi -> { - boolean groupInstanceArtifactRemoved = gi.getGroupInstanceArtifacts() != null && - gi.getGroupInstanceArtifacts().remove(artifactId); - boolean groupInstanceArtifactUUIDRemoved = gi.getGroupInstanceArtifactsUuid() != null && - gi.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); - + boolean groupInstanceArtifactRemoved = gi.getGroupInstanceArtifacts() != null && gi.getGroupInstanceArtifacts().remove(artifactId); + boolean groupInstanceArtifactUUIDRemoved = + gi.getGroupInstanceArtifactsUuid() != null && gi.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); return groupInstanceArtifactRemoved || groupInstanceArtifactUUIDRemoved; }).collect(Collectors.toList()); } - private ArtifactDataDefinition deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) { - + private ArtifactDataDefinition 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(); @@ -1474,12 +1360,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); resetMandatoryArtifactFields(foundArtifact); result = artifactToscaOperation.updateArtifactOnGraph(component, foundArtifact, parentType, artifactId, instanceId, true, true); - } - else if (cloneIsNeeded) { + } else if (cloneIsNeeded) { log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false); - } - else { + } else { log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId); result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false); } @@ -1489,33 +1373,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return result.left().value(); } - private Either, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) { - + 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(); + 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 { + } else { foundInstance = componentInstanceOpt.get(); fetchArtifactsFromInstance(artifactId, artifacts, foundInstance); } - } - else { + } else { fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts); } if (result == null) { if (artifacts.containsKey(artifactId)) { result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance)); - } - else { + } else { result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND); } } @@ -1525,28 +1405,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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(ArtifactDataDefinition::getUniqueId, i -> i)); + currArtifacts = component.getDeploymentArtifacts().values().stream() + .collect(Collectors.toMap(ArtifactDataDefinition::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(ArtifactDataDefinition::getUniqueId, Function.identity())); + currArtifacts = component.getArtifacts().values().stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } } if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { - currArtifacts = component.getToscaArtifacts() - .values() - .stream() - .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); + currArtifacts = component.getToscaArtifacts().values().stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } @@ -1556,19 +1430,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private void fetchArtifactsFromInstance(String artifactId, Map artifacts, ComponentInstance instance) { Map currArtifacts; if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) { - currArtifacts = instance.getDeploymentArtifacts() - .values() - .stream() - .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); + currArtifacts = instance.getDeploymentArtifacts().values().stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } } if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) { - currArtifacts = instance.getArtifacts() - .values() - .stream() - .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); + currArtifacts = instance.getArtifacts().values().stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity())); if (MapUtils.isNotEmpty(currArtifacts)) { artifacts.putAll(currArtifacts); } @@ -1621,10 +1491,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return error; } - private ArtifactDefinition handleDownload(String componentId, String artifactId, ComponentTypeEnum componentType, - Component parent) { - Either artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, - parent.getUniqueId()); + private ArtifactDefinition handleDownload(String componentId, String artifactId, ComponentTypeEnum componentType, Component parent) { + Either artifactById = artifactToscaOperation + .getArtifactById(componentId, artifactId, componentType, parent.getUniqueId()); if (artifactById.isRight()) { throw new StorageException(artifactById.right().value()); } @@ -1635,25 +1504,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return artifactDefinition; } - private Either handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName, + 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"); + 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 (operation.isCreateOrLink() && !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 { + } else { artifactLabel = operationName; } } @@ -1663,22 +1528,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } 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))); + 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); @@ -1686,7 +1548,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } artifactInfo.setArtifactLabel(artifactLabel); - return Either.left(ActionStatus.OK); } @@ -1695,11 +1556,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> artifacts; if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId); - } - else { + } else { artifacts = artifactToscaOperation.getArtifacts(componentId); } - if (artifacts.isLeft()) { for (String label : artifacts.left().value().keySet()) { if (label.equals(artifactLabel)) { @@ -1716,14 +1575,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo, ComponentTypeEnum componentType) { - Either, StorageOperationStatus> artifacts = getArtifacts(componentType, - parentComponent, componentId, artifactInfo.getArtifactGroupType()); + Either, StorageOperationStatus> artifacts = getArtifacts(componentType, parentComponent, componentId, + artifactInfo.getArtifactGroupType()); String artifactName = artifactInfo.getArtifactName(); - if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){ - if (artifacts.left().value().values().stream() - .anyMatch(ad -> artifactName.equals(ad.getArtifactName()) - //check whether it is the same artifact we hold (by label) - && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){ + if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())) { + if (artifacts.left().value().values().stream().anyMatch(ad -> artifactName.equals(ad.getArtifactName()) + //check whether it is the same artifact we hold (by label) + && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))) { return false; } } @@ -1735,61 +1593,47 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) { Either, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation - .getAllInterfacesOfResource(componentId, true, true); - - if (allInterfacesOfResource.isLeft()){ - return allInterfacesOfResource.left().value() - .values() - .stream().map(InterfaceDefinition :: getOperationsMap) - .flatMap(map -> map.values().stream()) - .map(OperationDataDefinition::getImplementation) - .filter(Objects::nonNull) - .noneMatch(add -> artifactName.equals(add.getArtifactName()) - && !artifactLabel.equals(add.getArtifactLabel())); + .getAllInterfacesOfResource(componentId, true, true); + if (allInterfacesOfResource.isLeft()) { + return allInterfacesOfResource.left().value().values().stream().map(InterfaceDefinition::getOperationsMap) + .flatMap(map -> map.values().stream()).map(OperationDataDefinition::getImplementation).filter(Objects::nonNull) + .noneMatch(add -> artifactName.equals(add.getArtifactName()) && !artifactLabel.equals(add.getArtifactLabel())); } return true; } private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) { Either, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation - .getAllInterfacesOfResource(componentId, true, true); - - if (allInterfacesOfResource.isLeft()){ - return allInterfacesOfResource.left().value() - .values() - .stream().map(InterfaceDefinition :: getOperationsMap) - .flatMap(map -> map.values().stream()) - .map(OperationDataDefinition::getImplementation) - .filter(Objects::nonNull) - .noneMatch(add -> artifactLabel.equals(add.getArtifactLabel())); + .getAllInterfacesOfResource(componentId, true, true); + if (allInterfacesOfResource.isLeft()) { + return allInterfacesOfResource.left().value().values().stream().map(InterfaceDefinition::getOperationsMap) + .flatMap(map -> map.values().stream()).map(OperationDataDefinition::getImplementation).filter(Objects::nonNull) + .noneMatch(add -> artifactLabel.equals(add.getArtifactLabel())); } return true; } private Either, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent, - String componentId, ArtifactGroupTypeEnum artifactGroupType) { + String componentId, + ArtifactGroupTypeEnum artifactGroupType) { Either, StorageOperationStatus> artifactsResponse; if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId); - } - else { + } else { artifactsResponse = artifactToscaOperation.getArtifacts(componentId); } if (artifactsResponse.isRight() && artifactsResponse.right().value() == StorageOperationStatus.NOT_FOUND) { log.debug("failed to retrieve artifacts for {} ", componentId); return Either.right(artifactsResponse.right().value()); } - return Either.left(artifactsResponse.left().value().entrySet() - .stream() - .filter(x -> artifactGroupType == x.getValue().getArtifactGroupType()) - .collect(Collectors.toMap(Entry::getKey, Entry::getValue))); + return Either.left(artifactsResponse.left().value().entrySet().stream().filter(x -> artifactGroupType == x.getValue().getArtifactGroupType()) + .collect(Collectors.toMap(Entry::getKey, Entry::getValue))); } // *************************************************************** - - private Either createArtifact(Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, - ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { - + private Either createArtifact(Component parent, String parentId, ArtifactDefinition artifactInfo, + byte[] decodedPayload, ComponentTypeEnum componentTypeEnum, + AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); if (artifactData == null) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); @@ -1807,29 +1651,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } // set on graph object id of artifact in ES! artifactInfo.setEsId(artifactData.getId()); - Either operationResult; if (interfaceType != null && operationName != null) { // lifecycle artifact Operation operation = convertToOperation(artifactInfo, operationName); - Either result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); + Either result = interfaceLifecycleOperation + .updateInterfaceOperation(parentId, interfaceType, operationName, operation); if (result.isRight()) { throw new StorageException(result.right().value()); } operationResult = Either.right(result.left().value()); - } - else { + } else { // information/deployment/api artifacts NodeTypeEnum nodeType = convertParentType(componentTypeEnum); - Either result = artifactToscaOperation.addArtifactToComponent( - artifactInfo, parent, nodeType, true, instanceId); + Either result = artifactToscaOperation + .addArtifactToComponent(artifactInfo, parent, nodeType, true, instanceId); if (result.isRight()) { throw new StorageException(result.right().value()); } ArtifactDefinition artifactDefinition = result.left().value(); artifactData.setId(artifactDefinition.getEsId()); operationResult = Either.left(artifactDefinition); - if (generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum) != StorageOperationStatus.OK) { throw new StorageException(generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum)); } @@ -1841,24 +1683,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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); + foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst() + .orElse(null); } return foundInstance; } private void validateDeploymentArtifact(final ArtifactDefinition artifactInfo, final Component component) { final ComponentTypeEnum componentType = component.getComponentType(); - if (componentType != ComponentTypeEnum.RESOURCE && - componentType != ComponentTypeEnum.SERVICE && - componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { - log.debug("Invalid component type '{}' for artifact. " - + "Expected Resource, Component or Resource Instance", componentType.getValue()); - throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, - componentType.getValue(), "Service, Resource or ResourceInstance", componentType.getValue()); + if (componentType != ComponentTypeEnum.RESOURCE && componentType != ComponentTypeEnum.SERVICE + && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { + log.debug("Invalid component type '{}' for artifact. " + "Expected Resource, Component or Resource Instance", componentType.getValue()); + throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, componentType.getValue(), + "Service, Resource or ResourceInstance", componentType.getValue()); } final String artifactType = artifactInfo.getArtifactType(); final ArtifactConfiguration artifactConfiguration = loadArtifactTypeConfig(artifactType).orElse(null); @@ -1869,21 +1706,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (componentType == ComponentTypeEnum.RESOURCE || componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { final Resource resource = (Resource) component; final ResourceTypeEnum resourceType = resource.getResourceType(); - validateResourceType(resourceType, artifactInfo, artifactConfiguration.getResourceTypes()); } - validateArtifactExtension(artifactConfiguration, artifactInfo); } - private void validateHeatArtifact(final Component parentComponent, final String componentId, - final ArtifactDefinition artifactDefinition) { + private void validateHeatArtifact(final Component parentComponent, final String componentId, final ArtifactDefinition artifactDefinition) { final String artifactType = artifactDefinition.getArtifactType(); final ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.parse(artifactType); if (artifactTypeEnum == null) { return; } - switch (artifactTypeEnum) { case HEAT: case HEAT_VOL: @@ -1898,9 +1731,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private void setArtifactTimeout(final ArtifactDefinition newArtifactInfo, - final ArtifactDefinition existingArtifactInfo) { - + private void setArtifactTimeout(final ArtifactDefinition newArtifactInfo, final ArtifactDefinition existingArtifactInfo) { final String artifactType = newArtifactInfo.getArtifactType(); final ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.parse(artifactType); if (artifactTypeEnum == null) { @@ -1926,7 +1757,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } @VisibleForTesting - void validateDeploymentArtifactTypeIsLegalForParent(ArtifactDefinition artifactInfo, ArtifactTypeEnum artifactType, Map resourceDeploymentArtifacts) { + void validateDeploymentArtifactTypeIsLegalForParent(ArtifactDefinition artifactInfo, ArtifactTypeEnum artifactType, + Map resourceDeploymentArtifacts) { if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) { log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); @@ -1937,14 +1769,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (artifactType == null) { return Optional.empty(); } - final List artifactConfigurationList = - ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts(); + final List artifactConfigurationList = ConfigurationManager.getConfigurationManager().getConfiguration() + .getArtifacts(); if (CollectionUtils.isEmpty(artifactConfigurationList)) { return Optional.empty(); } - - return artifactConfigurationList.stream() - .filter(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType)) + return artifactConfigurationList.stream().filter(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType)) .findFirst(); } @@ -1952,25 +1782,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // extract heat parameters if (artifactInfo.getPayloadData() != null) { String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData())); - Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo - .getArtifactType()); + Either, ResultStatusEnum> heatParameters = ImportUtils + .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType()); if (heatParameters.isRight() && (heatParameters.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND)) { log.info("failed to parse heat parameters "); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo - .getArtifactType()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType()); return Either.right(responseFormat); - } - else if (heatParameters.isLeft() && heatParameters.left().value() != null) { + } else if (heatParameters.isLeft() && heatParameters.left().value() != null) { artifactInfo.setListHeatParameters(heatParameters.left().value()); } } return Either.left(true); - } @VisibleForTesting - void validateArtifactExtension(final ArtifactConfiguration artifactConfiguration, - final ArtifactDefinition artifactDefinition) { + void validateArtifactExtension(final ArtifactConfiguration artifactConfiguration, final ArtifactDefinition artifactDefinition) { final List acceptedTypes = artifactConfiguration.getAcceptedTypes(); /* * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted. @@ -1980,7 +1807,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } final String artifactName = artifactDefinition.getArtifactName(); final String fileExtension = FilenameUtils.getExtension(artifactName); - if (fileExtension == null || !acceptedTypes.contains(fileExtension.toLowerCase())) { final String artifactType = artifactDefinition.getArtifactType(); log.debug("File extension \"{}\" is not allowed for artifact type \"{}\"", fileExtension, artifactType); @@ -1989,18 +1815,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } @VisibleForTesting - void validateHeatEnvDeploymentArtifact(final Component parentComponent, final String parentId, - final ArtifactDefinition artifactInfo) { + void validateHeatEnvDeploymentArtifact(final Component parentComponent, final String parentId, final ArtifactDefinition artifactInfo) { final Wrapper heatMDWrapper = new Wrapper<>(); final Wrapper payloadWrapper = new Wrapper<>(); - validateYaml(artifactInfo); validateHeatExist(parentComponent.getUniqueId(), parentId, heatMDWrapper, artifactInfo, parentComponent.getComponentType()); - if (!heatMDWrapper.isEmpty()) { fillArtifactPayload(payloadWrapper, heatMDWrapper.getInnerElement()); } - if (!heatMDWrapper.isEmpty()) { validateEnvVsHeat(artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement()); } @@ -2012,13 +1834,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (eitherArtifactData.isLeft()) { byte[] data = eitherArtifactData.left().value().getDataAsArray(); payloadWrapper.setInnerElement(Base64.encodeBase64(data)); - } - else { + } else { log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName()); throw new StorageException(DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value())); } - } - else { + } else { payloadWrapper.setInnerElement(artifactDefinition.getPayloadData()); } } @@ -2028,13 +1848,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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, TypeUtils.ToscaTagNamesEnum.PARAMETERS); + Either, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils + .findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS); if (eitherHeatEnvProperties.isRight()) { log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName()); throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat Env"); } - Either, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS); + Either, ResultStatusEnum> eitherHeatProperties = ImportUtils + .findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS); if (eitherHeatProperties.isRight()) { log.debug("Invalid heat format for file:{}", heatArtifact.getArtifactName()); throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat"); @@ -2043,8 +1864,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Set heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet(); heatEnvPropertiesKeys.removeAll(heatPropertiesKeys); if (!heatEnvPropertiesKeys.isEmpty()) { - log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName()); - throw new ByActionStatusComponentException(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName()); + log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), + heatArtifact.getArtifactName()); + throw new ByActionStatusComponentException(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), + heatArtifact.getArtifactName()); } } @@ -2059,28 +1882,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private void validateSingleDeploymentArtifactName(final String artifactName, final Component parentComponent) { boolean artifactNameFound = false; - final Iterator parentDeploymentArtifactsItr = - getDeploymentArtifacts(parentComponent, null).iterator(); - + final Iterator parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, null).iterator(); while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) { artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()); } if (artifactNameFound) { final ComponentTypeEnum componentType = parentComponent.getComponentType(); log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName); - throw new ByActionStatusComponentException(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, - componentType.getValue(), parentComponent.getName(), artifactName); + throw new ByActionStatusComponentException(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, componentType.getValue(), + parentComponent.getName(), artifactName); } } - private void validateHeatExist(String componentId, String parentRiId, Wrapper heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, - ComponentTypeEnum componentType) { + private void validateHeatExist(String componentId, String parentRiId, Wrapper heatArtifactMDWrapper, + ArtifactDefinition heatEnvArtifact, ComponentTypeEnum componentType) { final Either res = artifactToscaOperation .getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, componentId, componentType); if (res.isRight()) { throw new ByActionStatusComponentException(ActionStatus.MISSING_HEAT); } - heatArtifactMDWrapper.setInnerElement(res.left().value()); } @@ -2096,14 +1916,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } @VisibleForTesting - void validateResourceType(final ResourceTypeEnum resourceType, final ArtifactDefinition artifactInfo, - final List typeList) { + void validateResourceType(final ResourceTypeEnum resourceType, final ArtifactDefinition artifactInfo, final List typeList) { if (CollectionUtils.isEmpty(typeList) || typeList.contains(resourceType.getValue())) { return; } final String listToString = typeList.stream().collect(Collectors.joining(", ")); - throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, - artifactInfo.getArtifactGroupType().getType(), listToString, resourceType.getValue()); + throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactGroupType().getType(), + listToString, resourceType.getValue()); } @VisibleForTesting @@ -2114,17 +1933,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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()); + 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()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName()); return Either.right(responseFormat); } } @@ -2139,8 +1957,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } final List deploymentArtifacts = new ArrayList<>(); if (ComponentTypeEnum.RESOURCE == componentType && ciId != null) { - final Either getRI = - getRIFromComponent(component, ciId, null, null, null); + final Either getRI = getRIFromComponent(component, ciId, null, null, null); if (getRI.isRight()) { return Collections.emptyList(); } @@ -2163,73 +1980,61 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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) { + 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 + .buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel()); + } else { uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel()); } artifactInfo.setUniqueId(uniqueId); artifactInfo.setEsId(uniqueId); id = uniqueId; - } - else { + } else { artifactInfo.setUniqueId(artifactId); artifactInfo.setEsId(artifactId); } @@ -2241,7 +2046,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD)); } return Either.left(true); - } @VisibleForTesting @@ -2254,11 +2058,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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.right( + componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH))); } - return Either.left(true); } @@ -2267,21 +2070,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.info("artifact type is missing operation ignored"); throw new ByActionStatusComponentException(ActionStatus.MISSING_ARTIFACT_TYPE); } - if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) { log.info("artifact type cannot be changed operation ignored"); throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } } - private Either validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - + private Either validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, + ArtifactDefinition currentArtifact) { if (Objects.nonNull(artifactInfo) && Objects.nonNull(currentArtifact)) { if (artifactInfo.getArtifactGroupType() == null) { artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); - } else if (!currentArtifact.getArtifactGroupType() - .getType() - .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) { + } 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)); } @@ -2289,126 +2089,93 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(artifactInfo); } - private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) { - + 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())) { + 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())) { + 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())) { + 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())) { + 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())) { + 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())) { + 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())) { + 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())) { + 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())) { + 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())) { + .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())) { + 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() != 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())) { + 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()) { + 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())) { + if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) { log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue()); parameter.setDefaultValue(currentParam.getDefaultValue()); } @@ -2416,12 +2183,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType()); parameter.setType(currentParam.getType()); } - if (parameter.getDescription() != null && !parameter.getDescription() - .equalsIgnoreCase(currentParam.getDescription())) { + 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()); @@ -2432,7 +2197,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private Map getMapOfParameters(List currentParameters) { - Map currentParamsMap = new HashMap<>(); for (HeatParameterDefinition param : currentParameters) { currentParamsMap.put(param.getUniqueId(), param); @@ -2446,14 +2210,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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 + .right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH))); } - return Either.left(true); } @@ -2471,16 +2234,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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))); + 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 updateArtifactFlow(Component parent, String parentId, String artifactId, - ArtifactDefinition artifactInfo, byte[] decodedPayload, - ComponentTypeEnum componentType, AuditingActionEnum auditingAction) { + ArtifactDefinition artifactInfo, byte[] decodedPayload, + ComponentTypeEnum componentType, AuditingActionEnum auditingAction) { DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); if (artifactData == null) { BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT); @@ -2490,9 +2253,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Entry on graph is updated. Update artifact in ES"); // Changing previous and current artifactId for auditing String currArtifactId = artifactInfo.getUniqueId(); - NodeTypeEnum parentType = convertParentType(componentType); - if (decodedPayload == null) { if (!artifactInfo.getMandatory() || artifactInfo.getEsId() != null) { Either artifactFromCassandra = artifactCassandraDao.getArtifact(artifactInfo.getEsId()); @@ -2507,15 +2268,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { artifactInfo.setEsId(artifactInfo.getUniqueId()); artifactData.setId(artifactInfo.getUniqueId()); } - - Either result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, - parent, artifactId, parentType, parentId, true); + Either result = artifactToscaOperation + .updateArtifactOnResource(artifactInfo, parent, artifactId, parentType, parentId, true); if (result.isRight()) { throw new StorageException(result.right().value()); } ArtifactDefinition artifactDefinition = result.left().value(); updateGeneratedIdInHeatEnv(parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType); - StorageOperationStatus storageOperationStatus = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); if (storageOperationStatus != StorageOperationStatus.OK) { throw new StorageException(storageOperationStatus); @@ -2529,42 +2288,47 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(artifactDefinition); } - private String updateGeneratedIdInHeatEnv(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) { + private String updateGeneratedIdInHeatEnv(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, + ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) { if (NodeTypeEnum.Resource == parentType) { - return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType, false); + return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parent, parentId, artifactId, artifactInfo, artifactDefinition, + parentType, false); } return artifactDefinition.getUniqueId(); } - private String updateGeneratedIdInHeatEnv(Map deploymentArtifacts, Component parentComponent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType, boolean isInstanceArtifact) { + private String updateGeneratedIdInHeatEnv(Map deploymentArtifacts, Component parentComponent, String parentId, + String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, + NodeTypeEnum parentType, boolean isInstanceArtifact) { String artifactUniqueId; artifactUniqueId = artifactDefinition.getUniqueId(); String artifactType = artifactInfo.getArtifactType(); - if ((ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || - ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || - ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)) - && !artifactUniqueId.equals(artifactId)) { + if ((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 - Optional> findFirst = deploymentArtifacts.entrySet() - .stream() - .filter(a -> artifactId.equals(a.getValue().getGeneratedFromId())) - .findFirst(); + Optional> findFirst = deploymentArtifacts.entrySet().stream() + .filter(a -> artifactId.equals(a.getValue().getGeneratedFromId())).findFirst(); if (findFirst.isPresent()) { ArtifactDefinition artifactEnvInfo = findFirst.get().getValue(); artifactEnvInfo.setIsFromCsar(artifactDefinition.getIsFromCsar()); artifactEnvInfo.setArtifactChecksum(null); if (isInstanceArtifact) { - artifactToscaOperation.updateHeatEnvArtifactOnInstance(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId); + artifactToscaOperation + .updateHeatEnvArtifactOnInstance(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId); } else { - artifactToscaOperation.updateHeatEnvArtifact(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId); + artifactToscaOperation + .updateHeatEnvArtifact(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId); } } } return artifactUniqueId; } - private String updateGeneratedIdInHeatEnvOnInstance(ComponentInstance parent, Component parentComponent, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) { - return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parentComponent, parent.getUniqueId(),artifactId, artifactInfo, artifactDefinition, parentType, true); + private String updateGeneratedIdInHeatEnvOnInstance(ComponentInstance parent, Component parentComponent, String artifactId, + ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, + NodeTypeEnum parentType) { + return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parentComponent, parent.getUniqueId(), artifactId, artifactInfo, + artifactDefinition, parentType, true); } @VisibleForTesting @@ -2572,7 +2336,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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); @@ -2581,11 +2344,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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 result = Either.left(true); if (isDeploymentArtifact(artifactInfo)) { @@ -2593,18 +2354,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String artifactType = artifactInfo.getArtifactType(); String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName()); PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension); - final Optional pmDictionaryError = validateIfPmDictionary(artifactType, decodedPayload); if (pmDictionaryError.isPresent()) { return Either.right(pmDictionaryError.get()); } - Either isPayloadValid = payloadType.isValid(decodedPayload); if (isPayloadValid.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType); return Either.right(responseFormat); } - if (payloadType.isHeatRelated()) { log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType); result = extractHeatParameters(artifactInfo); @@ -2613,13 +2371,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (result.isRight()) { return Either.right(result.right().value()); } - } // 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("In artifact: {} Payload is missing.",artifactInfo.getArtifactName()); + log.debug("In artifact: {} Payload is missing.", artifactInfo.getArtifactName()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); return Either.right(responseFormat); } @@ -2629,26 +2388,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private Optional validateIfPmDictionary(String artifactType, byte[] decodedPayload) { - return new PMDictionaryValidator() - .validateIfPmDictionary(artifactType, decodedPayload) - .map(this::preparePmDictionaryResponse); + return new PMDictionaryValidator().validateIfPmDictionary(artifactType, decodedPayload).map(this::preparePmDictionaryResponse); } private ResponseFormat preparePmDictionaryResponse(String errorMessage) { return componentsUtils.getResponseFormat(ActionStatus.INVALID_PM_DICTIONARY_FILE, errorMessage); } - public Either deleteArtifactByInterface( - String resourceId, String userUserId, String artifactId, boolean inTransaction) { - - return toscaOperationFacade - .getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata) - .right().map(componentsUtils.toResponseFormat()) + public Either deleteArtifactByInterface(String resourceId, String userUserId, String artifactId, + boolean inTransaction) { + return toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata).right().map(componentsUtils.toResponseFormat()) .left().bind(parentComponent -> { User user = new User(userUserId); - return handleDelete(resourceId, artifactId, user, - parentComponent, - false, inTransaction); + return handleDelete(resourceId, artifactId, user, parentComponent, false, inTransaction); }); } @@ -2656,10 +2408,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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; @@ -2672,46 +2422,37 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } // download by MSO - public byte[] downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) { - + public byte[] 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(NULL_PARAMETER); throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } - // Normalizing artifact name artifactName = ValidationUtils.normalizeFileName(artifactName); - // Resource validation Resource resource = validateResourceNameAndVersion(resourceName, resourceVersion); String resourceId = resource.getUniqueId(); - // Service validation Service validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - Map artifacts = resource.getDeploymentArtifacts(); if (artifacts == null || artifacts.isEmpty()) { log.debug("Deployment artifacts of resource {} are not found", resourceId); throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName); } - ArtifactDefinition deploymentArtifact = null; - for (ArtifactDefinition artifactDefinition : artifacts.values()) { - if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName() - .equals(artifactName)) { + 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); throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName); } - // Downloading the artifact ImmutablePair downloadArtifactEither = downloadArtifact(deploymentArtifact); log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId()); @@ -2720,47 +2461,33 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { // download by MSO public byte[] downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) { - // General validation if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) { log.debug(NULL_PARAMETER); throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } - // Normalizing artifact name artifactName = ValidationUtils.normalizeFileName(artifactName); - // Service validation Service service = validateServiceNameAndVersion(serviceName, serviceVersion); - // ResourceInstance validation ComponentInstance resourceInstance = validateResourceInstance(service, resourceInstanceName); - Map artifacts = resourceInstance.getDeploymentArtifacts(); - final String finalArtifactName = artifactName; Predicate filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName); - - ArtifactDefinition deployableArtifact = artifacts==null ? null : - artifacts.values().stream() - .filter(filterArtifactByName) - .findFirst() - .orElse(null); - + ArtifactDefinition deployableArtifact = + artifacts == null ? null : artifacts.values().stream().filter(filterArtifactByName).findFirst().orElse(null); if (deployableArtifact == null) { log.debug("Deployment artifact with name {} not found", artifactName); throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); } - log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName); ImmutablePair downloadArtifactEither = downloadArtifact(deployableArtifact); - log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId()); return downloadArtifactEither.getRight(); } private ComponentInstance validateResourceInstance(Service service, String resourceInstanceName) { - List riList = service.getComponentInstances(); for (ComponentInstance ri : riList) { if (ri.getNormalizedName().equals(resourceInstanceName)) { @@ -2771,7 +2498,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private ComponentInstance validateResourceInstanceById(Component component, String resourceInstanceId) { - List riList = component.getComponentInstances(); for (ComponentInstance ri : riList) { if (ri.getUniqueId().equals(resourceInstanceId)) { @@ -2782,20 +2508,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } private Service validateServiceNameAndVersion(String serviceName, String serviceVersion) { - - Either, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName); + Either, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade + .getBySystemName(ComponentTypeEnum.SERVICE, serviceName); if (serviceListBySystemName.isRight()) { log.debug("Couldn't fetch any service with name {}", serviceName); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceListBySystemName - .right() - .value(), ComponentTypeEnum.SERVICE), serviceName); + throw new ByActionStatusComponentException( + 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); throw new ByActionStatusComponentException(ActionStatus.SERVICE_NOT_FOUND, serviceName); } - Service foundService = null; for (Service service : serviceList) { if (service.getVersion().equals(serviceVersion)) { @@ -2804,59 +2528,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { break; } } - if (foundService == null) { log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE - .getValue(), serviceVersion); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), + serviceVersion); } return foundService; } private Resource validateResourceNameAndVersion(String resourceName, String resourceVersion) { - - Either resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata); + 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); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceListBySystemName - .right() - .value()), resourceName); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), + resourceName); } return resourceListBySystemName.left().value(); } public byte[] downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) { // Validation - log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName); + log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, + artifactName); if (serviceName == null || serviceVersion == null || artifactName == null) { log.debug(NULL_PARAMETER); throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } - // Normalizing artifact name final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName); - // Service validation Service service = validateServiceNameAndVersion(serviceName, serviceVersion); // Looking for deployment or tosca artifacts String serviceId = service.getUniqueId(); - if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) { log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId); throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName); } - Optional foundArtifactOptl = Optional.empty(); - if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) { foundArtifactOptl = service.getDeploymentArtifacts().values().stream() - // filters artifact by name - .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); + // filters artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); } if ((!foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) { foundArtifactOptl = service.getToscaArtifacts().values().stream() - // filters TOSCA artifact by name - .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); + // 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); @@ -2864,8 +2582,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName); // Downloading the artifact - ImmutablePair downloadArtifactEither = downloadArtifact(foundArtifactOptl - .get()); + ImmutablePair downloadArtifactEither = downloadArtifact(foundArtifactOptl.get()); log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId()); return downloadArtifactEither.getRight(); } @@ -2883,21 +2600,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId); throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); } - return downloadArtifact(artifactDefinition); } - private Component validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType, - String containerComponentType) { - - ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType); + private Component 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); - + Either componentResult = toscaOperationFacade.getToscaFullElement(componentId); if (componentResult.isRight()) { - ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentForAudit == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND; + ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND + : componentForAudit == 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); @@ -2906,22 +2620,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return componentResult.left().value(); } - private void validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) { + private void validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, + ArtifactOperationInfo operation) { if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) { try { validateCanWorkOnComponent(component, userId); - }catch (ComponentException e) { + } catch (ComponentException e) { 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, e.getResponseFormat(), - component.getComponentType(), null); + handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, e.getResponseFormat(), component.getComponentType(), + null); throw e; } } } - private void validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) { - + private void validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, + ComponentTypeEnum componentType, ArtifactOperationInfo operation) { if (operation.isNotDownload()) { String role = user.getRole(); if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) { @@ -2933,15 +2648,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private User validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) { + private User validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, + ComponentTypeEnum componentType, boolean inTransaction) { User user; - try{ + try { user = validateUserExists(userId); - } catch(ByResponseFormatComponentException e){ + } catch (ByResponseFormatComponentException e) { ResponseFormat responseFormat = e.getResponseFormat(); handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId); throw e; - } catch(ByActionStatusComponentException e){ + } catch (ByActionStatusComponentException e) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId); throw e; @@ -2949,8 +2665,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return user; } - private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId, - ResponseFormat responseFormat, ComponentTypeEnum componentType, String userId){ + private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId, ResponseFormat responseFormat, + ComponentTypeEnum componentType, String userId) { User user = new User(); user.setUserId(userId); handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null); @@ -2963,7 +2679,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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; + 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; @@ -2987,7 +2704,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("Error when getting artifact from ES, error: {}", actionStatus); throw new ByActionStatusComponentException(actionStatus, artifactDefinition.getArtifactDisplayName()); } - DAOArtifactData DAOArtifactData = artifactfromES.left().value(); byte[] data = DAOArtifactData.getDataAsArray(); if (data == null) { @@ -3003,21 +2719,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return new DAOArtifactData(artifactInfo.getEsId(), artifactPayload); } - private void saveArtifactInCassandra(DAOArtifactData artifactData, Component parent, ArtifactDefinition artifactInfo, - String currArtifactId, String prevArtifactId, AuditingActionEnum auditingAction, ComponentTypeEnum componentType) { + private void saveArtifactInCassandra(DAOArtifactData artifactData, Component parent, ArtifactDefinition artifactInfo, String currArtifactId, + String prevArtifactId, AuditingActionEnum auditingAction, ComponentTypeEnum componentType) { CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData); - if (resourceUploadStatus == CassandraOperationStatus.OK) { log.debug("Artifact {} was saved in component {}.", artifactData.getId(), parent.getUniqueId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, - currArtifactId, responseFormat, componentType, null); - } - else { + handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat, + componentType, null); + } else { BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT); log.info(FAILED_SAVE_ARTIFACT); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat, + componentType, null); throw new StorageException(resourceUploadStatus); } } @@ -3052,66 +2767,57 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - - public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { + public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, + String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { User user = userBusinessLogic.getUser(userUserId, inTransaction); return createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user, groupType); } - public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) { + 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()); + 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) { + 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, Component component, NodeTypeEnum parentType, String instanceId) { + public Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, + Component component, NodeTypeEnum parentType, String instanceId) { return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, component, parentType, true, instanceId); } private Either createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) { - byte[] payload = payloadStr.getBytes(); - DAOArtifactData artifactData = createEsArtifactData(artifactDefinition, payload); return Either.left(artifactData); } @@ -3120,51 +2826,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param artifactDefinition * @return */ - public Either generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier, + public Either generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, + 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(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, + shouldLock, inTransaction).left() + .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); } - public Either forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier, - boolean shouldLock, boolean inTransaction, String instanceId) { + public Either forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, + ComponentTypeEnum componentType, 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(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, + shouldLock, inTransaction).left() + .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); } @VisibleForTesting - Either updateArtifactOnGroupInstance(Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) { + Either updateArtifactOnGroupInstance(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(); + 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()); - + 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, instanceId, updatedGroupInstances); + Either, StorageOperationStatus> status = toscaOperationFacade + .updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances); if (status.isRight()) { log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils - .convertFromStorageResponse(status.right() - .value()), clonedBeforeGenerate.getArtifactDisplayName()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), + clonedBeforeGenerate.getArtifactDisplayName()); return Either.right(responseFormat); } } @@ -3181,11 +2889,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { sb.append("parameters:\n"); if (heatParameters != null) { heatParameters.sort(Comparator.comparing(HeatParameterDataDefinition::getName)); - List empltyHeatValues = new ArrayList<>(); - for (HeatParameterDefinition heatParameterDefinition : heatParameters) { - String heatValue = heatParameterDefinition.getCurrentValue(); if (!ValidationUtils.validateStringNotEmpty(heatValue)) { heatValue = heatParameterDefinition.getDefaultValue(); @@ -3198,29 +2903,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (type != null) { switch (type) { case BOOLEAN: - sb.append(" ") - .append(heatParameterDefinition.getName()) - .append(":") - .append(" ") - .append(Boolean.parseBoolean(heatValue)) - .append("\n"); + 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"); + 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"); + sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n"); break; default: String value = heatValue; @@ -3233,14 +2925,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { value = "\"" + value + "\""; } } - sb.append(" ") - .append(heatParameterDefinition.getName()) - .append(":") - .append(" ") - .append(value); + sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value); sb.append("\n"); break; - } } } @@ -3249,18 +2936,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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()))) { + if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) + || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) { sb.append(" \"\"").append("\n"); - } - else { + } else { sb.append(" ").append("\n"); } }); } } sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - // DE265919 fix return sb.toString().replaceAll("\\\\n", "\n"); } @@ -3270,41 +2955,42 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param payload * @return */ - public Either generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, 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, 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, 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()) { - + public Either generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, + ComponentTypeEnum componentType, 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, 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, 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(); DAOArtifactData artifactData = null; - if (artifactDataRes.isLeft()) { artifactData = artifactDataRes.left().value(); - } - else { + } 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); - + 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()); @@ -3324,127 +3010,111 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } DAOArtifactData = artifactfromES.left().value(); oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(DAOArtifactData.getDataAsArray()); - } - else { + } else { oldCheckSum = artifactDefinition.getArtifactChecksum(); - } Either updateArifactDefinitionStatus = null; - if (shouldLock) { try { lockComponent(component, "Update Artifact - lock resource: "); - }catch (ComponentException e){ - handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition - .getUniqueId(), e.getResponseFormat(), component.getComponentType(), null); + } catch (ComponentException e) { + handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, + artifactDefinition.getUniqueId(), e.getResponseFormat(), component.getComponentType(), null); throw e; } } try { if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) { - artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get()); - updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component - ,artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true); - log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition - .getArtifactType(), artifactDefinition.getEsId()); + updateArifactDefinitionStatus = artifactToscaOperation + .updateArtifactOnResource(artifactDefinition, component, artifactDefinition.getUniqueId(), componentType.getNodeType(), + instanceId, true); + 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()); + 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); - + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, + artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, + resourceInstanceName); return Either.right(responseFormat); } - } - else { + } else { 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.updateArtifactOnResource(artifactDefinition, component, - artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true); - + log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), + artifactDefinition.getEsId()); + updateArifactDefinitionStatus = artifactToscaOperation + .updateArtifactOnResource(artifactDefinition, component, artifactDefinition.getUniqueId(), componentType.getNodeType(), + instanceId, true); log.trace("Update Payload {}", artifactDefinition.getEsId()); } if (updateArifactDefinitionStatus.isLeft()) { - artifactDefinition = updateArifactDefinitionStatus.left().value(); artifactData.setId(artifactDefinition.getUniqueId()); CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); - if (saveArtifactStatus == CassandraOperationStatus.OK) { if (!inTransaction) { janusGraphDao.commit(); } log.debug("Artifact Saved In cassandra {}", 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 { + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, + artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, + resourceInstanceName); + } else { if (!inTransaction) { janusGraphDao.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); - + 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()); + } 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); - + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, + artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, + resourceInstanceName); return Either.right(responseFormat); - } - } - finally { + } finally { if (shouldLock) { - graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType() - .getNodeType()); + 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(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) { - + 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); @@ -3454,30 +3124,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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(ArtifactTemplateInfo::getFileName) - .collect(Collectors.toList())); - json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() - : heatParameters); + : updatedRequiredArtifacts.stream().filter( + e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())) + .map(ArtifactTemplateInfo::getFileName).collect(Collectors.toList())); + json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() : heatParameters); return json; } - public Either updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) { - + public Either 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, false) : artifactInfo; + ArtifactDefinition artifactDefinitionFromJson = + artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class, false) : artifactInfo; String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); - Either uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId, - artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true); - + Either uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, + operation, artifactUniqueId, artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true); return Either.left(uploadArtifactToService.left().value()); } - private Either handleUpdateHeatEnvAndHeatMeta(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, - Component parent, String originData, String origMd5, ArtifactOperationInfo operation) { + private Either handleUpdateHeatEnvAndHeatMeta(String componentId, ArtifactDefinition artifactInfo, + AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, Component parent, String originData, + String origMd5, ArtifactOperationInfo operation) { if (origMd5 != null) { validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); if (ArrayUtils.isNotEmpty(artifactInfo.getPayloadData())) { @@ -3490,7 +3159,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return updateHeatEnvParamsAndMetadata(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5); } - private Either updateHeatEnvParamsAndMetadata(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent, + private Either updateHeatEnvParamsAndMetadata(String componentId, String artifactId, + ArtifactDefinition artifactInfo, User user, + AuditingActionEnum auditingAction, Component parent, ComponentTypeEnum componentType, String origMd5) { Either getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user); if (getRI.isRight()) { @@ -3502,61 +3173,59 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { throw new ByResponseFormatComponentException(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())) { + if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType() + .equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) { throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); } List currentHeatEnvParams = currArtifact.getListHeatParameters(); List updatedHeatEnvParams = artifactInfo.getListHeatParameters(); - // upload if (origMd5 != null) { - Either, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, - artifactId, componentType, ri.getName(), currentHeatEnvParams, updatedHeatEnvParams, currArtifact.getArtifactName()); + Either, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, + parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams, updatedHeatEnvParams, + currArtifact.getArtifactName()); if (uploadParamsValidationResult.isRight()) { throw new ByResponseFormatComponentException(uploadParamsValidationResult.right().value()); } artifactInfo.setListHeatParameters(updatedHeatEnvParams); } - - Either validateAndConvertHeatParamers = validateAndConvertHeatParameters(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType()); + Either validateAndConvertHeatParamers = validateAndConvertHeatParameters(artifactInfo, + ArtifactTypeEnum.HEAT_ENV.getType()); if (validateAndConvertHeatParamers.isRight()) { throw new ByResponseFormatComponentException(validateAndConvertHeatParamers.right().value()); } - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) { // fill reduced heat env parameters List for updating boolean updateRequired = replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams); if (updateRequired) { currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); currArtifact.setListHeatParameters(currentHeatEnvParams); - Either updateArtifactRes = artifactToscaOperation.updateArtifactOnResource( - currArtifact, parent, currArtifact.getUniqueId(), componentType.getNodeType(), componentId, true); + Either updateArtifactRes = artifactToscaOperation + .updateArtifactOnResource(currArtifact, parent, currArtifact.getUniqueId(), componentType.getNodeType(), componentId, true); if (updateArtifactRes.isRight()) { log.debug("Failed to update artifact on graph - {}", artifactId); throw new StorageException(updateArtifactRes.right().value()); } - StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(ri, updateArtifactRes.left().value().getUniqueId(), parent.getUniqueId()); + StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(ri, updateArtifactRes.left().value().getUniqueId(), + parent.getUniqueId()); if (error != StorageOperationStatus.OK) { throw new StorageException(error); } } } - updateHeatMetaDataIfNeeded(componentId,user,auditingAction,componentType, parent,ri,artifactInfo); + updateHeatMetaDataIfNeeded(componentId, user, auditingAction, componentType, parent, ri, artifactInfo); StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType); if (error != StorageOperationStatus.OK) { throw new StorageException(error); } - return Either.left(currArtifact); } - private void - updateHeatMetaDataIfNeeded(String componentId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent, ComponentInstance resourceInstance, ArtifactDefinition updatedHeatEnvArtifact) { + private void updateHeatMetaDataIfNeeded(String componentId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, + Component parent, ComponentInstance resourceInstance, ArtifactDefinition updatedHeatEnvArtifact) { String heatArtifactId = updatedHeatEnvArtifact.getGeneratedFromId(); - Either getArtifactRes = getArtifactFromRI(parent, resourceInstance, componentId, heatArtifactId, auditingAction, user); + Either getArtifactRes = getArtifactFromRI(parent, resourceInstance, componentId, heatArtifactId, + auditingAction, user); if (getArtifactRes.isRight()) { throw new ByResponseFormatComponentException(getArtifactRes.right().value()); } @@ -3564,16 +3233,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (isUpdateHeatMetaDataNeeded(updatedHeatEnvArtifact, heatArtifactToUpdate)) { validateHeatMetaData(updatedHeatEnvArtifact); updateHeatMetadataFromHeatEnv(updatedHeatEnvArtifact, heatArtifactToUpdate); - Either updateArtifactRes = artifactToscaOperation.updateArtifactOnResource(heatArtifactToUpdate, parent, - heatArtifactToUpdate.getUniqueId(), componentType.getNodeType(), componentId, false); - + Either updateArtifactRes = artifactToscaOperation + .updateArtifactOnResource(heatArtifactToUpdate, parent, heatArtifactToUpdate.getUniqueId(), componentType.getNodeType(), componentId, + false); if (updateArtifactRes.isRight()) { log.debug("Failed to update artifact on graph - {}", heatArtifactId); throw new StorageException(updateArtifactRes.right().value()); } ArtifactDefinition artifactDefinition = updateArtifactRes.left().value(); - updateGeneratedIdInHeatEnvOnInstance(resourceInstance, parent, heatArtifactId, heatArtifactToUpdate, artifactDefinition, componentType.getNodeType()); - StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(resourceInstance, artifactDefinition.getUniqueId(), parent.getUniqueId()); + updateGeneratedIdInHeatEnvOnInstance(resourceInstance, parent, heatArtifactId, heatArtifactToUpdate, artifactDefinition, + componentType.getNodeType()); + StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(resourceInstance, artifactDefinition.getUniqueId(), + parent.getUniqueId()); if (error != StorageOperationStatus.OK) { throw new StorageException(error); } @@ -3599,7 +3270,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { origHeat.setTimeout(updatedHeatEnv.getTimeout()); } - private boolean replaceCurrHeatValueWithUpdatedValue(List currentHeatEnvParams, List updatedHeatEnvParams) { + private boolean replaceCurrHeatValueWithUpdatedValue(List currentHeatEnvParams, + List updatedHeatEnvParams) { boolean isUpdate = false; List currentParamsNames = currentHeatEnvParams.stream().map(x -> x.getName()).collect(Collectors.toList()); for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { @@ -3624,24 +3296,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - private Either updateHeatParams(String componentId, ArtifactDefinition artifactEnvInfo, AuditingActionEnum auditingAction, Component parent, - ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) { + private Either updateHeatParams(String componentId, ArtifactDefinition artifactEnvInfo, + AuditingActionEnum auditingAction, Component parent, + ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, + boolean needToUpdateGroup) { Either insideEither = null; String currentHeatId = currHeatArtifact.getUniqueId(); - String esArtifactId = currHeatArtifact.getEsId(); Either artifactFromES = artifactCassandraDao.getArtifact(esArtifactId); if (artifactFromES.isRight()) { StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromES.right().value()); throw new StorageException(storageResponse, currHeatArtifact.getArtifactDisplayName()); } - DAOArtifactData DAOArtifactData = artifactFromES.left().value(); ArtifactDefinition updatedHeatArt = currHeatArtifact; List updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters(); List currentHeatEnvParams = currHeatArtifact.getListHeatParameters(); List newHeatEnvParams = new ArrayList<>(); - if (CollectionUtils.isNotEmpty(updatedHeatEnvParams) && CollectionUtils.isNotEmpty(currentHeatEnvParams)) { //TODO: improve complexity - currently N^2 String paramName; @@ -3655,8 +3326,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); if (!paramType.getValidator().isValid(updatedParamValue, null)) { - throw new ByActionStatusComponentException(ActionStatus.INVALID_HEAT_PARAMETER_VALUE, - ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); + throw new ByActionStatusComponentException(ActionStatus.INVALID_HEAT_PARAMETER_VALUE, ArtifactTypeEnum.HEAT_ENV.getType(), + paramType.getType(), paramName); } currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); newHeatEnvParams.add(currHeatParam); @@ -3666,9 +3337,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (!newHeatEnvParams.isEmpty()) { currHeatArtifact.setListHeatParameters(currentHeatEnvParams); - Either operationStatus = artifactToscaOperation.updateArtifactOnResource( - currHeatArtifact, parent, currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId, true); - + Either operationStatus = artifactToscaOperation + .updateArtifactOnResource(currHeatArtifact, parent, currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId, + true); if (operationStatus.isRight()) { log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId()); throw new StorageException(operationStatus.right().value()); @@ -3677,26 +3348,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (!updatedHeatArt.getDuplicated() || DAOArtifactData.getId() == null) { DAOArtifactData.setId(updatedHeatArt.getEsId()); } - saveArtifactInCassandra(DAOArtifactData, parent, artifactEnvInfo, currentHeatId, updatedHeatArt - .getUniqueId(), auditingAction, componentType); + saveArtifactInCassandra(DAOArtifactData, parent, artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), auditingAction, + componentType); insideEither = Either.left(updatedHeatArt); } } Either updateHeatEnvArtifact; if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) { artifactEnvInfo.setArtifactChecksum(null); - updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent, artifactEnvInfo, currentHeatId, updatedHeatArt - .getUniqueId(), componentType.getNodeType(), componentId); - } - else { + updateHeatEnvArtifact = artifactToscaOperation + .updateHeatEnvArtifact(parent, artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), + componentId); + } else { //TODO Andrey check if componentId = parent.getUniqeId - updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, parent, componentType - .getNodeType()); - + updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, parent, componentType.getNodeType()); } if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) { - ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, - updateHeatEnvArtifact.left().value(), parent); + ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent); if (result != ActionStatus.OK) { throw new ByActionStatusComponentException(result); } @@ -3707,7 +3375,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return insideEither; } - 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()); @@ -3715,34 +3382,33 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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()); + .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) { - + 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); + 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()); @@ -3753,14 +3419,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } 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); + 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) { + private Either getRIFromComponent(Component component, String riID, String artifactId, + AuditingActionEnum auditingAction, User user) { ResponseFormat responseFormat = null; List ris = component.getComponentInstances(); for (ComponentInstance ri : ris) { @@ -3774,7 +3442,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(responseFormat); } - private Either getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { + 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()) { @@ -3783,8 +3452,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId()); - handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri - .getName()); + handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, + ri.getName()); return Either.right(responseFormat); } @@ -3792,14 +3461,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { ArtifactDefinition ret; if (eitherArtifact.isLeft()) { ret = eitherArtifact.left().value(); - } - else { + } else { ret = eitherArtifact.right().value().getImplementationArtifact(); } return ret; } - public byte[] downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) { + public byte[] downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, + ResourceCommonInfo resourceCommonInfo) { Component component = getComponentByUuid(componentType, componentUuid); resourceCommonInfo.setResourceName(component.getName()); return downloadArtifact(component.getAllArtifacts(), artifactUUID, component.getName()); @@ -3814,10 +3483,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param artifactUUID * @return */ - public byte[] downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, - String resourceInstanceName, String artifactUUID) { + public byte[] downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, + String artifactUUID) { ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName); - if (resourceInstance != null) { return downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, resourceInstance.getName()); } else { @@ -3837,24 +3505,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @return */ public ArtifactDefinition uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, - String componentUuid, ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) { + String componentUuid, ResourceCommonInfo resourceCommonInfo, + ArtifactOperationInfo operation) { Either actionResult; Component component; String componentId; ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false); String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either getComponentRes = - fetchLatestComponentMetadataOrThrow(componentType, componentUuid); - + Either getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid); ComponentMetadataDataDefinition componentMetadataDataDefinition = getComponentRes.left().value().getMetadataDataDefinition(); componentId = componentMetadataDataDefinition.getUniqueId(); String componentName = componentMetadataDataDefinition.getName(); - - if (!componentMetadataDataDefinition - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + if (!componentMetadataDataDefinition.getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { component = checkoutParentComponent(componentType, componentId, userId); if (component != null) { componentId = component.getUniqueId(); @@ -3862,9 +3525,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } resourceCommonInfo.setResourceName(componentName); - - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, - origMd5, data, null, null, null, null); + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, + null); return actionResult.left().value(); } @@ -3879,43 +3541,30 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation * @return */ - public ArtifactDefinition uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, - ArtifactOperationInfo operation) { + public ArtifactDefinition uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, + String resourceInstanceName, ArtifactOperationInfo operation) { Either actionResult; 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 = - fetchLatestComponentMetadataOrThrow(componentType, componentUuid, resourceInstanceName); - if (!getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getUniqueId(), userId); + Either getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid, + resourceInstanceName); + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId); } if (component == null) { componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName); - } - else { + } else { componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName); } componentInstanceId = componentRiPair.getRight().getUniqueId(); componentId = componentRiPair.getLeft().getUniqueId(); ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, - operation, null, artifactInfo, origMd5, data, null, null, - componentId, ComponentTypeEnum.findParamByType(componentType)); - + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, + data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); return actionResult.left().value(); } @@ -3928,29 +3577,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentUuid * @param artifactUUID * @param resourceCommonInfo - * @param operation TODO + * @param operation TODO * @return */ - public ArtifactDefinition updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, - ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) { + public ArtifactDefinition updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, + String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo, + ArtifactOperationInfo operation) { Either actionResult; Component component; String componentId; - String artifactId ; + String artifactId; ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class); String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either getComponentRes = - fetchLatestComponentMetadataOrThrow(componentType, componentUuid); + Either getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid); 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())) { + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { component = checkoutParentComponent(componentType, componentId, userId); if (component != null) { componentId = component.getUniqueId(); @@ -3959,14 +3602,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } resourceCommonInfo.setResourceName(componentName); artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, componentId, componentType); - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, - origMd5, data, null, null, null, null); + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, + null); if (actionResult.isRight()) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult - .right() - .value()); + log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult.right().value()); } - return actionResult.left().value(); } @@ -3982,9 +3622,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation TODO * @return */ - public ArtifactDefinition updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - ArtifactOperationInfo operation) { - + public ArtifactDefinition updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, + String resourceInstanceName, String artifactUUID, ArtifactOperationInfo operation) { Either actionResult; Component component = null; String componentInstanceId; @@ -3992,37 +3631,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String artifactId; String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - ImmutablePair componentRiPair = null; - Either getComponentRes = - fetchLatestComponentMetadataOrThrow(componentType, componentUuid); - if (!getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getUniqueId(), userId); + Either getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid); + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId); } if (component == null) { componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName); - } - else { + } else { componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName); } componentInstanceId = componentRiPair.getRight().getUniqueId(); componentId = componentRiPair.getLeft().getUniqueId(); artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID); ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum - .findParamByType(componentType)); + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, + origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); return actionResult.left().value(); } - private Either updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){ + private Either updateOperationArtifact(String componentId, String interfaceType, String operationUuid, + ArtifactDefinition artifactInfo) { Either componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId); if (componentStorageOperationStatusEither.isRight()) { StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value(); @@ -4030,28 +3659,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); } Component storedComponent = componentStorageOperationStatusEither.left().value(); - - Optional optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType); - if(!optionalInterface.isPresent()) { + Optional optionalInterface = InterfaceOperationUtils + .getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType); + if (!optionalInterface.isPresent()) { log.debug("Failed to get resource interface for resource Id {}", componentId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType)); } - //fetch the operation from storage InterfaceDefinition gotInterface = optionalInterface.get(); Map operationsMap = gotInterface.getOperationsMap(); - Optional optionalOperation = operationsMap.values() - .stream() - .filter(o -> o.getUniqueId().equals(operationUuid)) - .findFirst(); + Optional optionalOperation = operationsMap.values().stream().filter(o -> o.getUniqueId().equals(operationUuid)).findFirst(); if (!optionalOperation.isPresent()) { log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId); return Either.right(responseFormat); } - Operation operation = optionalOperation.get(); - ArtifactDefinition implementationArtifact = operation.getImplementationArtifact(); + ArtifactDefinition implementationArtifact = operation.getImplementationArtifact(); implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID()); implementationArtifact.setUniqueId(artifactInfo.getUniqueId()); implementationArtifact.setArtifactName(artifactInfo.getArtifactName()); @@ -4062,15 +3686,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { implementationArtifact.setEsId(artifactInfo.getEsId()); operation.setImplementation(implementationArtifact); gotInterface.setOperationsMap(operationsMap); - Either, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither = - interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface)); - if (interfaceDefinitionStorageOperationStatusEither.isRight()){ + Either, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither = interfaceOperation + .updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface)); + if (interfaceDefinitionStorageOperationStatusEither.isRight()) { StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value(); - ActionStatus actionStatus = - componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus); return Either.right(componentsUtils.getResponseFormat(actionStatus)); } - return Either.left(artifactInfo); } @@ -4085,129 +3707,107 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation * @return */ - public Either updateArtifactOnInterfaceOperationByResourceUUID( - String data, HttpServletRequest request, ComponentTypeEnum componentType, - String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID, - ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) { + public Either updateArtifactOnInterfaceOperationByResourceUUID(String data, HttpServletRequest request, + ComponentTypeEnum componentType, + String componentUuid, String interfaceUUID, + String operationUUID, String artifactUUID, + ResourceCommonInfo resourceCommonInfo, + ArtifactOperationInfo operation) { Wrapper errorWrapper = new Wrapper<>(); Either updateArtifactResult; String componentId = null; ArtifactDefinition existingArtifactInfo = null; String interfaceName = 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 = - fetchLatestComponentMetadata(componentType, componentUuid) - .right().map(as -> { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(as)); - return as; - }); - + Either getComponentRes = fetchLatestComponentMetadata(componentType, componentUuid).right().map(as -> { + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(as)); + return as; + }); 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())) { + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { Component component = checkoutParentComponent(componentType, componentId, userId); if (component != null) { componentId = component.getUniqueId(); componentName = component.getName(); } - } resourceCommonInfo.setResourceName(componentName); } - - if(errorWrapper.isEmpty()){ + if (errorWrapper.isEmpty()) { Either interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID); if (interfaceNameEither.isRight()) { errorWrapper.setInnerElement(interfaceNameEither.right().value()); - } - else { + } else { interfaceName = interfaceNameEither.left().value(); } - - if(errorWrapper.isEmpty()){ + if (errorWrapper.isEmpty()) { Either toscaComponentEither = toscaOperationFacade.getToscaElement(componentId); if (toscaComponentEither.isRight()) { StorageOperationStatus status = toscaComponentEither.right().value(); log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status); errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); } - if (errorWrapper.isEmpty()) { NodeTypeEnum parentType = convertParentType(componentType); - final List existingDeploymentArtifacts = - getDeploymentArtifacts(toscaComponentEither.left().value(),null); - for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){ - if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){ + final List existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), null); + for (ArtifactDefinition artifactDefinition : existingDeploymentArtifacts) { + if (artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())) { existingArtifactInfo = artifactDefinition; break; } } - if(existingArtifactInfo != null){ + if (existingArtifactInfo != null) { return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo); } } } } - if (errorWrapper.isEmpty()) { - updateArtifactResult = handleArtifactRequestAndFlatten(componentId, userId, componentType, operation, - artifactUUID, artifactInfo, origMd5, data, interfaceName, operationUUID); + updateArtifactResult = handleArtifactRequestAndFlatten(componentId, userId, componentType, operation, artifactUUID, artifactInfo, origMd5, + data, interfaceName, operationUUID); } else { updateArtifactResult = Either.right(errorWrapper.getInnerElement()); } - return updateArtifactResult; } - private Either handleArtifactRequestAndFlatten( - String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, - String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData, String interfaceName, - String operationName) { + private Either handleArtifactRequestAndFlatten(String componentId, String userId, + ComponentTypeEnum componentType, + ArtifactOperationInfo operation, String artifactId, + ArtifactDefinition artifactInfo, String origMd5, + String originData, String interfaceName, + String operationName) { try { - return handleArtifactRequest(componentId, userId, componentType, operation, - artifactId, artifactInfo, origMd5, originData, interfaceName, - operationName, null, null) - .right().map(op -> { - log.debug("Unexpected value returned while calling handleArtifactRequest: {}", op); - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - }); + return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, + operationName, null, null).right().map(op -> { + log.debug("Unexpected value returned while calling handleArtifactRequest: {}", op); + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + }); } catch (ComponentException e) { return Either.right(e.getResponseFormat()); } } - private Either fetchLatestComponentMetadataOrThrow( - ComponentTypeEnum componentType, String componentUuid - ) { + private Either fetchLatestComponentMetadataOrThrow(ComponentTypeEnum componentType, String componentUuid) { return fetchLatestComponentMetadataOrThrow(componentType, componentUuid, componentUuid); } - private Either fetchLatestComponentMetadataOrThrow( - ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName - ) { + private Either fetchLatestComponentMetadataOrThrow(ComponentTypeEnum componentType, String componentUuid, + String resourceInstanceName) { return fetchLatestComponentMetadata(componentType, componentUuid).right().map(as -> { throw new ByActionStatusComponentException(as, resourceInstanceName); }); } - private Either fetchLatestComponentMetadata( - ComponentTypeEnum componentType, String componentUuid - ) { - return toscaOperationFacade - .getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true) - .right().map(sos -> { - log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, sos); - return componentsUtils.convertFromStorageResponse(sos, componentType); - }); + private Either fetchLatestComponentMetadata(ComponentTypeEnum componentType, String componentUuid) { + return toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true).right().map(sos -> { + log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, sos); + return componentsUtils.convertFromStorageResponse(sos, componentType); + }); } private Either fetchInterfaceName(String componentId, String interfaceUUID) { @@ -4218,10 +3818,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); } Component storedComponent = componentStorageOperationStatusEither.left().value(); - Optional optionalInterface = InterfaceOperationUtils .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID); - if(!optionalInterface.isPresent()) { + if (!optionalInterface.isPresent()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID)); } return Either.left(optionalInterface.get().getType()); @@ -4235,28 +3834,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentUuid * @param artifactUUID * @param resourceCommonInfo - * @param operation TODO + * @param operation TODO * @return */ - public ArtifactDefinition deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo, + public ArtifactDefinition deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, + String artifactUUID, ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) { - Either actionResult; Component component; - String componentId ; + String componentId; String artifactId; String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either getComponentRes = - fetchLatestComponentMetadataOrThrow(componentType, componentUuid); + Either getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid); 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())) { + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { component = checkoutParentComponent(componentType, componentId, userId); if (component != null) { componentId = component.getUniqueId(); @@ -4280,10 +3873,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param operation TODO * @return */ - public ArtifactDefinition deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, - String componentUuid, String resourceInstanceName, - String artifactUUID, ArtifactOperationInfo operation) { - + public ArtifactDefinition deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, + String resourceInstanceName, String artifactUUID, ArtifactOperationInfo operation) { Either actionResult; Component component = null; String componentInstanceId; @@ -4292,30 +3883,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = - fetchLatestComponentMetadataOrThrow(componentType, componentUuid); - if (!getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left() - .value() - .getMetadataDataDefinition() - .getUniqueId(), userId); + Either getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid); + if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId); } if (component == null) { componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName); - } - else { + } else { componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName); } componentInstanceId = componentRiPair.getRight().getUniqueId(); componentId = componentRiPair.getLeft().getUniqueId(); artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum - .findParamByType(componentType)); + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, + null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); return actionResult.left().value(); } @@ -4323,41 +3904,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { 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); + 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); + 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()); throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID); - } - else { + } else { artifactId = foundArtifact.getUniqueId(); } return artifactId; } @SuppressWarnings("unchecked") - public ArtifactDefinition createHeatEnvPlaceHolder(List createdArtifacts, ArtifactDefinition heatArtifact, - String envType, String parentId, NodeTypeEnum parentType, - String parentName, User user, Component component, + public ArtifactDefinition createHeatEnvPlaceHolder(List createdArtifacts, ArtifactDefinition heatArtifact, String envType, + String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, Map existingEnvVersions) { - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getDeploymentResourceInstanceArtifacts(); + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getDeploymentResourceInstanceArtifacts(); if (deploymentResourceArtifacts == null) { log.debug("no deployment artifacts are configured for generated artifacts"); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); @@ -4367,10 +3935,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { log.debug("no env type {} are configured for generated artifacts", envType); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } - String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); - ArtifactDefinition createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user - .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true); + ArtifactDefinition createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user.getUserId(), + ArtifactGroupTypeEnum.DEPLOYMENT, true); ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder; artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId()); artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); @@ -4384,16 +3951,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (parentType != NodeTypeEnum.ResourceInstance) { String checkSum = artifactToscaOperation.sortAndCalculateChecksumForHeatParameters(heatArtifact.getHeatParameters()); artifactHeatEnv.setArtifactChecksum(checkSum); - Either addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component, parentType, parentId); + Either addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component, + parentType, parentId); if (addHeatEnvArtifact.isRight()) { log.debug("failed to create heat env artifact on resource instance"); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact - .right() - .value(), false), "", null)); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance( + componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null)); } heatEnvPlaceholder = createArtifactPlaceHolder; - } - else { + } else { heatEnvPlaceholder = artifactHeatEnv; artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion()); setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder); @@ -4404,10 +3970,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } createdArtifacts.add(heatEnvPlaceholder); componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, - new ResourceCommonInfo(parentName, componentType.getValue()), - ResourceVersionInfo.newBuilder().build(), - ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(), - null, heatEnvPlaceholder, null); + new ResourceCommonInfo(parentName, componentType.getValue()), ResourceVersionInfo.newBuilder().build(), + ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(), null, heatEnvPlaceholder, null); return heatEnvPlaceholder; } @@ -4433,8 +3997,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (name == null) { name = heatArtifact.getArtifactLabel(); fileName = name + "." + envExtension; - } - else { + } else { fileName = name.replaceAll("." + heatExtension, "." + envExtension); } heatEnvArtifact.setArtifactName(fileName); @@ -4449,7 +4012,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } - public List handleArtifactsForInnerVfcComponent(List artifactsToHandle, Resource component, User user, List vfcsNewCreatedArtifacts, + public List handleArtifactsForInnerVfcComponent(List artifactsToHandle, Resource component, User user, + List vfcsNewCreatedArtifacts, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { ComponentTypeEnum componentType = component.getComponentType(); List uploadedArtifacts = new ArrayList<>(); @@ -4460,8 +4024,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { uploadedArtifacts.add(result.left().value()); } } catch (ComponentException e) { - log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, component - .getName(), e.getResponseFormat()); + log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, component.getName(), e.getResponseFormat()); if (operation.isCreateOrLink()) { vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); } @@ -4470,27 +4033,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return uploadedArtifacts; } - public Either handleLoadedArtifact(Component component, User user, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, - ComponentTypeEnum componentType, ArtifactDefinition artifactDefinition) { + public Either handleLoadedArtifact(Component component, User user, ArtifactOperationInfo operation, + boolean shouldLock, boolean inTransaction, ComponentTypeEnum componentType, + ArtifactDefinition artifactDefinition) { AuditingActionEnum auditingAction = detectAuditingType(operation, ""); String componentId = component.getUniqueId(); String artifactId = artifactDefinition.getUniqueId(); Either result; Wrapper errorWrapper = new Wrapper<>(); //artifact validation - artifactDefinition = validateArtifact(componentId, componentType, operation, - artifactId, artifactDefinition, auditingAction, user, - component, shouldLock, inTransaction); + artifactDefinition = validateArtifact(componentId, componentType, operation, artifactId, artifactDefinition, auditingAction, user, component, + shouldLock, inTransaction); switch (operation.getArtifactOperationEnum()) { case CREATE: - byte[] validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, null, null); - result = createArtifact(component, componentId, artifactDefinition, validPayload, - componentType, auditingAction, null, null); + byte[] validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, + component, null, null); + result = createArtifact(component, componentId, artifactDefinition, validPayload, componentType, auditingAction, null, null); break; case UPDATE: - validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, null, null); + validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, + null, null); result = handleUpdate(componentId, componentType, operation, artifactId, artifactDefinition, validPayload, null, null, null, null, - auditingAction, user, component, true); + auditingAction, user, component, true); break; case DELETE: result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, component)); @@ -4506,14 +4070,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { result = Either.left(handleLink(componentId, artifactDefinition, componentType, component)); break; default: - throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum()); + throw new UnsupportedOperationException( + "In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum()); } return result; } - public List handleArtifactsRequestForInnerVfcComponent(List artifactsToHandle, Resource component, User user, List vfcsNewCreatedArtifacts, - ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { - + public List handleArtifactsRequestForInnerVfcComponent(List artifactsToHandle, Resource component, + User user, List vfcsNewCreatedArtifacts, + ArtifactOperationInfo operation, boolean shouldLock, + boolean inTransaction) { List handleArtifactsResult; ComponentTypeEnum componentType = component.getComponentType(); List uploadedArtifacts = new ArrayList<>(); @@ -4524,12 +4090,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { for (ArtifactDefinition artifact : artifactsToHandle) { originData = ArtifactUtils.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); + actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), + artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction); uploadedArtifacts.add(actionResult.left().value()); } handleArtifactsResult = uploadedArtifacts; - }catch (ComponentException e){ + } catch (ComponentException e) { if (operation.isCreateOrLink()) { vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); } @@ -4538,36 +4104,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return handleArtifactsResult; } - private ComponentInstance getRelatedComponentInstance( - ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName - ) { + private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName) { String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); Option oComponent = Option.of(getComponentByUuid(componentType, componentUuid)); - return oComponent - .toTry(componentNotFound(componentType, componentUuid)) - .flatMap(component -> findFirstMatching(component, - ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName) - ).toTry(componentInstanceNotFound(componentType, resourceInstanceName, component)) - ).get(); + return oComponent.toTry(componentNotFound(componentType, componentUuid)).flatMap( + component -> findFirstMatching(component, ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)) + .toTry(componentInstanceNotFound(componentType, resourceInstanceName, component))).get(); } - private ImmutablePair getRelatedComponentComponentInstance( - Component component, String resourceInstanceName - ) { + private ImmutablePair getRelatedComponentComponentInstance(Component component, String resourceInstanceName) { String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); ComponentInstance componentInstance = findFirstMatching(component, - ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName) - ).toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get(); + ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)) + .toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get(); return new ImmutablePair<>(component, componentInstance); } - private ImmutablePair getRelatedComponentComponentInstance( - ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName - ) { + private ImmutablePair getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, + String resourceInstanceName) { Component component = getLatestComponentByUuid(componentType, componentUuid); - ComponentInstance componentInstance = findFirstMatching(component, - ci -> ci.getNormalizedName().equals(resourceInstanceName) - ).toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get(); + ComponentInstance componentInstance = findFirstMatching(component, ci -> ci.getNormalizedName().equals(resourceInstanceName)) + .toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get(); return new ImmutablePair<>(component, componentInstance); } @@ -4578,35 +4135,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { }; } - private Supplier componentInstanceNotFound( - ComponentTypeEnum componentType, String resourceInstanceName, Component component - ) { + private Supplier componentInstanceNotFound(ComponentTypeEnum componentType, String resourceInstanceName, Component component) { return () -> { log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName()); - return new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, - resourceInstanceName, + return new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, componentType.getValue(), component.getName()); }; } - private static Option findFirstMatching(Component component, Predicate filter) { - return Option.ofOptional(component.getComponentInstances() - .stream() - .filter(filter) - .findFirst()); - } - private byte[] downloadArtifact(Map artifacts, String artifactUUID, String componentName) { - ImmutablePair downloadArtifact; List artifactsList = null; ArtifactDefinition deploymentArtifact; if (artifacts != null && !artifacts.isEmpty()) { - artifactsList = artifacts.values() - .stream() - .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID() - .equals(artifactUUID)) - .collect(Collectors.toList()); + 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); @@ -4625,8 +4168,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { StorageOperationStatus status = getComponentRes.right().value(); log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); - } - else { + } else { component = getComponentRes.left().value(); } return component; @@ -4639,15 +4181,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { StorageOperationStatus status = getComponentRes.right().value(); log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); - } - else { + } 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; throw new ByActionStatusComponentException(status); - } - else { + } else { component = value.get(0); } } @@ -4668,41 +4208,39 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } throw new ByActionStatusComponentException(actionStatus, artifactUUID); } - artifacts = getArtifactsRes.left() - .value() - .values() - .stream() - .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID() - .equals(artifactUUID)) - .collect(Collectors.toList()); + 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); + log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, + parentId, actionStatus); throw new ByActionStatusComponentException(actionStatus, artifactUUID); } 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()); + 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); + log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, + parentId, actionStatus); throw new ByActionStatusComponentException(actionStatus, artifactUUID); } return latestArtifact.getUniqueId(); } private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId) { - Component component = null; User modifier = userBusinessLogic.getUser(userId, false); - LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API); - Either checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true); + 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()); + log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, + checkoutRes.right().value().getStatus()); throw new ByResponseFormatComponentException(checkoutRes.right().value()); } return checkoutRes.left().value(); @@ -4716,4 +4254,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public List getConfiguration() { return ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts(); } + + public enum ArtifactOperationEnum { + CREATE, UPDATE, DELETE, DOWNLOAD, LINK; + + public static boolean isCreateOrLink(ArtifactOperationEnum operation) { + return operation == CREATE || operation == LINK; + } + } } 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 a44ed3c8c7..3c06e8b818 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; @@ -25,7 +24,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; -import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -36,7 +34,6 @@ import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; @@ -64,20 +61,15 @@ 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 final Logger log = Logger.getLogger(AttributeBusinessLogic.class); private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {}. Error - {}"; @Autowired - public AttributeBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public AttributeBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); } /** @@ -88,20 +80,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return AttributeDefinition if created successfully Or ResponseFormat */ - public Either createAttribute(String resourceId, - AttributeDefinition newAttributeDef, - String userId) { + public Either createAttribute(String resourceId, AttributeDefinition newAttributeDef, String userId) { Either result = null; validateUserExists(userId); - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance() - .logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + 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); @@ -109,40 +96,33 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { 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())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName())); } Map eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); // validate property default values - Either defaultValuesValidation = validateAttributeDefaultValue(newAttributeDef, - eitherAllDataTypes); + Either defaultValuesValidation = validateAttributeDefaultValue(newAttributeDef, eitherAllDataTypes); if (defaultValuesValidation.isRight()) { return Either.right(defaultValuesValidation.right().value()); } - handleAttributeDefaultValue(newAttributeDef, eitherAllDataTypes); - // add the new attribute to resource on graph + // need to get StorageOperationStatus and convert to ActionStatus from + // componentsUtils - Either either = toscaOperationFacade - .addAttributeOfResource(resource, newAttributeDef); + Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); if (either.isRight()) { - result = Either.right(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), - resource.getName())); + 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); @@ -152,50 +132,43 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { private Either validateAttributeDefaultValue(final AttributeDefinition attributeDefinition, final Map dataTypes) { - if (!attributeOperation.isAttributeTypeValid(attributeDefinition)) { - log.info("Invalid type for attribute '{}' type '{}'", attributeDefinition.getName(), - attributeDefinition.getType()); + log.info("Invalid type for attribute '{}' type '{}'", attributeDefinition.getName(), attributeDefinition.getType()); final ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, attributeDefinition - .getType(), attributeDefinition.getName()); + .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, attributeDefinition.getType(), attributeDefinition.getName()); return Either.right(responseFormat); } String type = attributeDefinition.getType(); String innerType = null; if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - final ImmutablePair propertyInnerTypeValid = attributeOperation.isAttributeInnerTypeValid( - attributeDefinition, dataTypes); + final ImmutablePair propertyInnerTypeValid = attributeOperation + .isAttributeInnerTypeValid(attributeDefinition, dataTypes); innerType = propertyInnerTypeValid.getLeft(); if (!Boolean.TRUE.equals(propertyInnerTypeValid.getRight())) { - log.info("Invalid inner type for attribute '{}' type '{}', dataTypeCount '{}'", - attributeDefinition.getName(), attributeDefinition.getType(), dataTypes.size()); + log.info("Invalid inner type for attribute '{}' type '{}', dataTypeCount '{}'", attributeDefinition.getName(), + attributeDefinition.getType(), dataTypes.size()); final ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, - attributeDefinition.getName()); + .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, attributeDefinition.getName()); return Either.right(responseFormat); } } if (!attributeOperation.isAttributeDefaultValueValid(attributeDefinition, dataTypes)) { - log.info("Invalid default value for attribute '{}' type '{}'", attributeDefinition.getName(), - attributeDefinition.getType()); + log.info("Invalid default value for attribute '{}' type '{}'", attributeDefinition.getName(), attributeDefinition.getType()); ResponseFormat responseFormat; if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, - attributeDefinition.getName(), type, innerType, - (String) attributeDefinition.get_default()); + responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, attributeDefinition.getName(), type, innerType, + (String) attributeDefinition.get_default()); } else { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, - attributeDefinition.getName(), type, (String) attributeDefinition.get_default()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, attributeDefinition.getName(), type, + (String) attributeDefinition.get_default()); } return Either.right(responseFormat); - } return Either.left(true); } - private void handleAttributeDefaultValue(final AttributeDefinition newAttributeDefinition, - final Map dataTypes) { + private void handleAttributeDefaultValue(final AttributeDefinition newAttributeDefinition, final Map dataTypes) { final ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDefinition.getType()); final PropertyValueConverter converter = type.getConverter(); // get inner type @@ -208,19 +181,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } } if (newAttributeDefinition.get_default() != null) { - newAttributeDefinition.set_default(converter - .convert((String) newAttributeDefinition.get_default(), innerType, dataTypes)); + newAttributeDefinition.set_default(converter.convert((String) newAttributeDefinition.get_default(), innerType, dataTypes)); } } private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { boolean isExist = false; if (attributes != null) { - isExist = attributes.stream().anyMatch( - p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getOwnerId(), resourceUid)); + isExist = attributes.stream().anyMatch(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getOwnerId(), resourceUid)); } return isExist; - } /** @@ -229,27 +199,22 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either getAttribute(String resourceId, String attributeId, - String userId) { - + public Either getAttribute(String resourceId, String attributeId, String userId) { validateUserExists(userId); - // 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 { // verify attribute exist in resource - Optional optionalAtt = attributes.stream().filter(att -> - att.getUniqueId().equals(attributeId)).findAny(); - return optionalAtt.>map(Either::left).orElseGet(() -> - Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""))); + Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId)).findAny(); + return optionalAtt.>map(Either::left) + .orElseGet(() -> Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""))); } } @@ -262,14 +227,12 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either updateAttribute(String resourceId, String attributeId, - AttributeDefinition newAttDef, String userId) { + public Either updateAttribute(String resourceId, String attributeId, AttributeDefinition 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); + 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)); } @@ -280,55 +243,41 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { 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()); } Map eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - // validate attribute default values - Either defaultValuesValidation = validateAttributeDefaultValue(newAttDef, - eitherAllDataTypes); + Either defaultValuesValidation = validateAttributeDefaultValue(newAttDef, eitherAllDataTypes); if (defaultValuesValidation.isRight()) { return Either.right(defaultValuesValidation.right().value()); } - // add the new property to resource on graph - StorageOperationStatus validateAndUpdateAttribute = attributeOperation - .validateAndUpdateAttribute(newAttDef, eitherAllDataTypes); + StorageOperationStatus validateAndUpdateAttribute = attributeOperation.validateAndUpdateAttribute(newAttDef, eitherAllDataTypes); if (validateAndUpdateAttribute != StorageOperationStatus.OK) { - log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, - validateAndUpdateAttribute); + log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute); result = Either.right(componentsUtils - .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), - resource.getName())); + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName())); } - - Either eitherAttUpdate = toscaOperationFacade - .updateAttributeOfResource(resource, newAttDef); - + 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())); + 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); } - } /** @@ -339,21 +288,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either deleteAttribute(String resourceId, String attributeId, - String userId) { - + public Either deleteAttribute(String resourceId, String attributeId, String userId) { Either result = null; - validateUserExists(userId); - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance() - .logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + 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); @@ -361,30 +304,23 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { 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); + 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); + StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName); if (eitherAttributeDelete != StorageOperationStatus.OK) { - result = Either.right(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), - resource.getName())); + result = Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName())); return result; } - result = Either.left(eitherAttributeExist.left().value()); return result; } finally { @@ -393,10 +329,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } } - public Either, ResponseFormat> getAttributesList(final String componentId, - final String userId) { + public Either, ResponseFormat> getAttributesList(final String componentId, final String userId) { validateUserExists(userId); - // Get the resource from DB final ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreAttributes(false); @@ -404,42 +338,62 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } - return Either.left(status.left().value().getAttributes()); } - public boolean isAttributeUsedByOperation(Component component, - AttributeDefinition propertyDefinitionEntry) { + public boolean isAttributeUsedByOperation(Component component, AttributeDefinition propertyDefinitionEntry) { // TODO - do we need this one return false; - // // Component's own interfaces + // Map interfaces = component.getInterfaces(); + // if(MapUtils.isNotEmpty(interfaces)){ + // for(Map.Entry interfaceEntry : interfaces.entrySet()) { + // if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) { + // return true; + // } + // } + // } + // + // // Component's child's component interfaces + // if(isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)){ + // return true; + // } + // + // // Component's parent's component interfaces + // Either, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId()); + // if(componentList.isLeft()){ + // for (Component parentComponent : componentList.left().value()) { + // if(isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)){ + // return true; + // } + // } + // } + // + // return false; } - - } 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 a640de0be7..fbfeaa5320 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 @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR; @@ -101,7 +100,6 @@ import org.springframework.beans.factory.annotation.Autowired; public abstract class BaseBusinessLogic { private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}"; - private static final Logger log = Logger.getLogger(BaseBusinessLogic.class); private static final String EMPTY_VALUE = null; private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}"; @@ -127,12 +125,11 @@ public abstract class BaseBusinessLogic { protected PolicyTypeOperation policyTypeOperation; protected ArtifactsOperations artifactToscaOperation; protected UserValidations userValidations; - DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { this.elementDao = elementDao; this.groupOperation = groupOperation; this.groupInstanceOperation = groupInstanceOperation; @@ -142,6 +139,12 @@ public abstract class BaseBusinessLogic { this.artifactToscaOperation = artifactToscaOperation; } + @SafeVarargs + static > boolean enumHasValueFilter(String name, Function enumGetter, T... enumValues) { + T enumFound = enumGetter.apply(name); + return Arrays.asList(enumValues).contains(enumFound); + } + @Autowired public void setUserAdmin(UserBusinessLogic userAdmin) { this.userAdmin = userAdmin; @@ -226,11 +229,10 @@ public abstract class BaseBusinessLogic { lockComponent(component.getUniqueId(), component, ecompErrorContext); } - protected boolean isVolumeGroup(List artifactsInGroup,List deploymentArtifacts) { + protected boolean isVolumeGroup(List artifactsInGroup, List deploymentArtifacts) { for (String artifactId : artifactsInGroup) { ArtifactDefinition artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId); - if (artifactDef != null - && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { + if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { return true; } } @@ -238,14 +240,14 @@ public abstract class BaseBusinessLogic { } protected void lockComponent(Component component, boolean shouldLock, String ecompErrorContext) { - if(shouldLock){ + if (shouldLock) { lockComponent(component.getUniqueId(), component, ecompErrorContext); } } protected void lockComponent(String componentId, Component component, String ecompErrorContext) { ActionStatus lock = lockElement(componentId, component, ecompErrorContext); - if (lock!= ActionStatus.OK) { + if (lock != ActionStatus.OK) { logAndThrowComponentException(lock, component.getUniqueId(), component.getName()); } } @@ -256,7 +258,7 @@ public abstract class BaseBusinessLogic { } } - private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name){ + private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name) { log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status); throw new ByActionStatusComponentException(status, name); } @@ -265,7 +267,6 @@ public abstract class BaseBusinessLogic { ComponentTypeEnum componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType); - if (lockResourceStatus == StorageOperationStatus.OK) { return ActionStatus.OK; } else { @@ -287,16 +288,18 @@ public abstract class BaseBusinessLogic { } // unlock resource graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); + } else { + log.debug("component is NULL"); } - else log.debug("component is NULL"); } protected void unlockComponent(boolean failed, Component component) { unlockComponent(failed, component, false); } + void unlockComponentById(boolean failed, String componentId) { Either component = toscaOperationFacade.getToscaElement(componentId); - if(component.isLeft()) { + if (component.isLeft()) { unlockComponent(failed, component.left().value(), false); } } @@ -310,7 +313,6 @@ public abstract class BaseBusinessLogic { } } - ComponentTypeEnum validateComponentType(String componentType) { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum == null) { @@ -322,9 +324,9 @@ public abstract class BaseBusinessLogic { } Component validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { - - Either toscaElement = toscaOperationFacade.getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter); - if(toscaElement.isRight()){ + Either toscaElement = toscaOperationFacade + .getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter); + if (toscaElement.isRight()) { handleGetComponentError(componentId, componentType, toscaElement.right().value()); } return validateComponentType(toscaElement.left().value(), componentType); @@ -342,21 +344,24 @@ public abstract class BaseBusinessLogic { Either, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); if (allDataTypesEither.isRight()) { JanusGraphOperationStatus status = allDataTypesEither.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))); + BeEcompErrorManager.getInstance() + .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, + ErrorSeverity.ERROR); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))); } Map allDataTypes = allDataTypesEither.left().value(); String propertyType = property.getType(); String innerType = getInnerType(property); // Specific Update Logic - Either isValid = - propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, - innerType, allDataTypes); + 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)) { - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } } else { Object object = isValid.left().value(); @@ -367,7 +372,7 @@ public abstract class BaseBusinessLogic { return newValue; } - String getInnerType(T property){ + String getInnerType(T property) { ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType()); log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType()); String innerType = null; @@ -389,35 +394,30 @@ public abstract class BaseBusinessLogic { public void validateCanWorkOnComponent(Component component, String userId) { ActionStatus actionStatus = ActionStatus.RESTRICTED_OPERATION; // verify resource is not archived - if (Boolean.TRUE.equals(component.isArchived())){ + if (Boolean.TRUE.equals(component.isArchived())) { actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED; throw new ByActionStatusComponentException(actionStatus, component.getName()); } - if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { log.debug("Component {} is not checked-out", component.getName()); throw new ByActionStatusComponentException(actionStatus); } - // verify userId is not null if (userId == null) { log.debug("Current user userId is null"); throw new ByActionStatusComponentException(actionStatus); } - // 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); throw new ByActionStatusComponentException(actionStatus); } - // verify resource is not deleted if (Boolean.TRUE.equals(component.getIsDeleted())) { log.debug("Component {} is marked as deleted", component.getUniqueId()); throw new ByActionStatusComponentException(actionStatus); } - } ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) { @@ -453,7 +453,8 @@ public abstract class BaseBusinessLogic { 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()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); return Either.right(responseFormat); } type = property.getType(); @@ -461,8 +462,10 @@ public abstract class BaseBusinessLogic { ImmutablePair propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes); innerType = propertyInnerTypeValid.getLeft(); if (Boolean.FALSE.equals(propertyInnerTypeValid.getRight())) { - log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(), dataTypes.size()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); + log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(), + dataTypes.size()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); return Either.right(responseFormat); } } @@ -470,14 +473,13 @@ public abstract class BaseBusinessLogic { 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()); + 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()); + responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); } return Either.right(responseFormat); - } return Either.left(true); } @@ -487,15 +489,14 @@ public abstract class BaseBusinessLogic { 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) { + 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)); } - } void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper errorWrapper) { @@ -504,7 +505,6 @@ public abstract class BaseBusinessLogic { log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId); errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } - } protected ToscaPropertyType getType(String propertyType) { @@ -525,7 +525,6 @@ public abstract class BaseBusinessLogic { ComponentTypeEnum componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType); - if (lockResourceStatus == StorageOperationStatus.OK) { return Either.left(true); } else { @@ -537,11 +536,10 @@ public abstract class BaseBusinessLogic { } } - protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) { - return toscaOperationFacade.getToscaElement(componentId, componentParametersView) - .left() - .on(err -> handleGetComponentError(componentId, componentType, err)); - + protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, + ComponentParametersView componentParametersView) { + return toscaOperationFacade.getToscaElement(componentId, componentParametersView).left() + .on(err -> handleGetComponentError(componentId, componentType, err)); } private Component handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) { @@ -550,14 +548,8 @@ public abstract class BaseBusinessLogic { throw new ByActionStatusComponentException(actionStatus, componentId); } - @SafeVarargs - static > boolean enumHasValueFilter(String name, Function enumGetter, T... enumValues) { - T enumFound = enumGetter.apply(name); - return Arrays.asList(enumValues).contains(enumFound); - } - String validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, - Map allDataTypes) { + Map allDataTypes) { String propertyType = property.getType(); String updatedInnerType = updateInnerType(property); Either isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, updatedInnerType, allDataTypes); @@ -565,8 +557,7 @@ public abstract class BaseBusinessLogic { if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { - throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( - JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); + throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } } else { Object object = isValid.left().value(); @@ -578,8 +569,7 @@ public abstract class BaseBusinessLogic { log.trace("After validateAndUpdateRules. pair = {}", pair); if (Boolean.FALSE.equals(pair.getRight())) { BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType); - throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( - JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); + throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } return newValue; } @@ -603,20 +593,19 @@ public abstract class BaseBusinessLogic { } private void failOnIllegalArgument() { - throw new ByActionStatusComponentException( - componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); + throw new ByActionStatusComponentException(componentsUtils + .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } - public Either validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map dataTypes) { + 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); + 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); @@ -640,12 +629,11 @@ public abstract class BaseBusinessLogic { return Either.left(convertedValue); } - private ImmutablePair validateAndUpdateRules(String propertyType, List rules, String innerType, Map dataTypes, boolean isValidate) { - + private 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); @@ -663,7 +651,6 @@ public abstract class BaseBusinessLogic { rule.setValue(newValue); } } - return ImmutablePair.of(null, true); } @@ -671,9 +658,7 @@ public abstract class BaseBusinessLogic { if (isEmptyValue(value)) { return true; } - PropertyTypeValidator validator = type.getValidator(); - return validator.isValid(value, innerType, dataTypes); } @@ -696,26 +681,22 @@ public abstract class BaseBusinessLogic { throw new ByActionStatusComponentException(actionStatus, params); } - public Either, ResponseFormat> declareProperties(final String userId, - final String componentId, - final ComponentTypeEnum componentTypeEnum, - final ComponentInstInputsMap componentInstInputsMap) { + public Either, ResponseFormat> declareProperties(final String userId, final String componentId, + final ComponentTypeEnum componentTypeEnum, + final ComponentInstInputsMap componentInstInputsMap) { return Either.left(new ArrayList<>()); } - public Either, ResponseFormat> declareAttributes(final String userId, - final String componentId, - final ComponentTypeEnum componentTypeEnum, - final ComponentInstOutputsMap componentInstOutputsMap) { + public Either, ResponseFormat> declareAttributes(final String userId, final String componentId, + final ComponentTypeEnum componentTypeEnum, + final ComponentInstOutputsMap componentInstOutputsMap) { return Either.left(new ArrayList<>()); } public List setInputConstraint(T inputDefinition) { - if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) - && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) { + if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) { return setConstraint(inputDefinition); } - return Collections.emptyList(); } @@ -725,32 +706,22 @@ public abstract class BaseBusinessLogic { if (inputPathArr.length > 1) { inputPathArr = ArrayUtils.remove(inputPathArr, 0); } - - Map dataTypeDefinitionMap = - applicationDataTypeCache.getAll().left().value(); - + Map dataTypeDefinitionMap = applicationDataTypeCache.getAll().left().value(); String propertyType = inputDefinition.getParentPropertyType(); - for (String anInputPathArr : inputPathArr) { if (ToscaType.isPrimitiveType(propertyType)) { - constraints.addAll( - dataTypeDefinitionMap.get(propertyType).getConstraints()); + constraints.addAll(dataTypeDefinitionMap.get(propertyType).getConstraints()); } else if (!ToscaType.isCollectionType(propertyType)) { - propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, - constraints); + propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, constraints); } } - return constraints; } - private String setConstraintForComplexType(Map dataTypeDefinitionMap, - String propertyType, - String anInputPathArr, + private String setConstraintForComplexType(Map dataTypeDefinitionMap, String propertyType, String anInputPathArr, List constraints) { String type = null; - List propertyDefinitions = - dataTypeDefinitionMap.get(propertyType).getProperties(); + List propertyDefinitions = dataTypeDefinitionMap.get(propertyType).getProperties(); for (PropertyDefinition propertyDefinition : propertyDefinitions) { if (propertyDefinition.getName().equals(anInputPathArr)) { if (ToscaType.isPrimitiveType(propertyDefinition.getType())) { @@ -761,18 +732,16 @@ public abstract class BaseBusinessLogic { break; } } - return type; } - protected void unlockRollbackWithException(Component component, RuntimeException e) { janusGraphDao.rollback(); graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType()); throw e; } - protected void unlockWithCommit(Component component){ + protected void unlockWithCommit(Component component) { ComponentTypeEnum componentType = component.getComponentType(); NodeTypeEnum nodeType = componentType.getNodeType(); janusGraphDao.commit(); @@ -796,17 +765,13 @@ public abstract class BaseBusinessLogic { } protected Component getComponent(final String componentId) throws BusinessLogicException { - final Either result = toscaOperationFacade.getToscaElement(componentId); - if (result.isRight()) { final StorageOperationStatus errorStatus = result.right().value(); - log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), - "Failed to fetch component information by component id, error {}", errorStatus); - throw new BusinessLogicException(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(errorStatus))); + log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), "Failed to fetch component information by component id, error {}", + errorStatus); + throw new BusinessLogicException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); } return result.left().value(); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java index f94528c64a..2fc012b720 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java @@ -17,42 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CADI; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; + import org.openecomp.sdc.common.api.HealthCheckInfo; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CADI; -import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; - @Component public class CADIHealthCheck { - private static CADIHealthCheck cadiHealthCheckInstance = new CADIHealthCheck();; - - private static HealthCheckInfo.HealthCheckStatus isCADIUpOrDown = DOWN; - private static final Logger log = Logger.getLogger(CADIHealthCheck.class.getName()); + private static CADIHealthCheck cadiHealthCheckInstance = new CADIHealthCheck(); + private static HealthCheckInfo.HealthCheckStatus isCADIUpOrDown = DOWN; public static CADIHealthCheck getCADIHealthCheckInstance() { return cadiHealthCheckInstance; } - public void setIsCADIUp(HealthCheckInfo.HealthCheckStatus cadiStatus) { - log.debug("Setting cadiHealthCheckInstance status to: {}", cadiStatus.toString()); - isCADIUpOrDown = cadiStatus; - } - public static HealthCheckInfo getCADIStatus() { log.debug("getCADIStatus: Checking whether CADI was up or down while its init."); String description = "OK"; - if (isCADIUpOrDown == DOWN){ + if (isCADIUpOrDown == DOWN) { description = "CADI filter failed initialization"; } - return new HealthCheckInfo(HC_COMPONENT_CADI, isCADIUpOrDown, null, - description); + return new HealthCheckInfo(HC_COMPONENT_CADI, isCADIUpOrDown, null, description); } + public void setIsCADIUp(HealthCheckInfo.HealthCheckStatus cadiStatus) { + log.debug("Setting cadiHealthCheckInstance status to: {}", cadiStatus.toString()); + isCADIUpOrDown = cadiStatus; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java index 4bfc6509c6..cadaf6fcbc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java @@ -13,10 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -51,42 +60,25 @@ 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.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - @org.springframework.stereotype.Component("capabilitiesBusinessLogic") public class CapabilitiesBusinessLogic extends BaseBusinessLogic { + private static final Logger LOGGER = LoggerFactory.getLogger(CapabilitiesBusinessLogic.class); private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS = "Failed to lock component {}. Response is {}"; private static final String DELETE_CAPABILITIES = "deleteCapability"; private static final String GET_CAPABILITIES = "getCapabilities"; private static final String EXCEPTION_OCCURRED_DURING_CAPABILITIES = "Exception occurred during {}. Response is {}"; - private final ICapabilityTypeOperation capabilityTypeOperation; - private CapabilitiesOperation capabilitiesOperation; private CapabilitiesValidation capabilitiesValidation; @Autowired - public CapabilitiesBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ICapabilityTypeOperation capabilityTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public CapabilitiesBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ICapabilityTypeOperation capabilityTypeOperation, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.capabilityTypeOperation = capabilityTypeOperation; } @@ -100,16 +92,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { this.capabilitiesOperation = capabilitiesOperation; } - public Either, ResponseFormat> createCapabilities(String componentId, - List capabilityDefinitions, + public Either, ResponseFormat> createCapabilities(String componentId, List capabilityDefinitions, User user, String errorContext, boolean lock) { - Either validateUserAndCapabilitiesEither = - validateUserAndCapabilities(user, componentId, errorContext, capabilityDefinitions); - if(validateUserAndCapabilitiesEither.isRight()) { + Either validateUserAndCapabilitiesEither = validateUserAndCapabilities(user, componentId, errorContext, + capabilityDefinitions); + if (validateUserAndCapabilitiesEither.isRight()) { return Either.right(validateUserAndCapabilitiesEither.right().value()); } - Component storedComponent = validateUserAndCapabilitiesEither.left().value(); - + Component storedComponent = validateUserAndCapabilitiesEither.left().value(); Either lockResult = lockComponentResult(lock, storedComponent, errorContext); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); @@ -122,16 +112,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - - private Either validateUserAndCapabilities(User user, String componentId, - String errorContext, - List capabilityDefinitions ) { + private Either validateUserAndCapabilities(User user, String componentId, String errorContext, + List capabilityDefinitions) { validateUserExists(user.getUserId()); Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { @@ -139,15 +127,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { } Component storedComponent = componentEither.left().value(); Either capabilitiesValidationEither = capabilitiesValidation - .validateCapabilities(capabilityDefinitions, storedComponent, false); + .validateCapabilities(capabilityDefinitions, storedComponent, false); if (capabilitiesValidationEither.isRight()) { return Either.right(capabilitiesValidationEither.right().value()); } return Either.left(storedComponent); } - private Either, ResponseFormat> createCapability(String componentId, - List capabilityDefinitions, + private Either, ResponseFormat> createCapability(String componentId, List capabilityDefinitions, Component storedComponent) { Either, StorageOperationStatus> result; List capabilitiesListStoredInComponent = null; @@ -157,32 +144,30 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { if (Objects.isNull(capabilityDefinitionToGetType)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } - capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType - .getType(), storedComponentCapabilities); + capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType.getType(), + storedComponentCapabilities); } List capabilitiesDefListToCreate; List capabilitiesToReturn; if (CollectionUtils.isNotEmpty(capabilitiesListStoredInComponent)) { - capabilitiesDefListToCreate = capabilityDefinitions.stream().map(capabilityDefinition -> - initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList()); + capabilitiesDefListToCreate = capabilityDefinitions.stream() + .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList()); capabilitiesToReturn = capabilitiesDefListToCreate; capabilitiesDefListToCreate.addAll(capabilitiesListStoredInComponent); result = capabilitiesOperation.updateCapabilities(componentId, capabilitiesDefListToCreate); } else { - capabilitiesToReturn = capabilityDefinitions.stream().map(capabilityDefinition -> - initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList()); + capabilitiesToReturn = capabilityDefinitions.stream() + .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList()); result = capabilitiesOperation.addCapabilities(componentId, capabilitiesToReturn); } if (result.isRight()) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result - .right().value(), storedComponent.getComponentType()), "")); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), "")); } - Map propertiesMap = - getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions); + Map propertiesMap = getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions); if (MapUtils.isNotEmpty(propertiesMap)) { - StorageOperationStatus storageOperationStatus = capabilitiesOperation - .createOrUpdateCapabilityProperties(componentId, propertiesMap); + StorageOperationStatus storageOperationStatus = capabilitiesOperation.createOrUpdateCapabilityProperties(componentId, propertiesMap); if (storageOperationStatus != StorageOperationStatus.OK) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(storageOperationStatus)); @@ -192,8 +177,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return Either.left(capabilitiesToReturn); } - public Either, ResponseFormat> updateCapabilities(String componentId, - List capabilityDefinitions, + public Either, ResponseFormat> updateCapabilities(String componentId, List capabilityDefinitions, User user, String errorContext, boolean lock) { validateUserExists(user.getUserId()); Either componentEither = getComponentDetails(componentId); @@ -202,11 +186,10 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { } Component storedComponent = componentEither.left().value(); Either capabilitiesValidationEither = capabilitiesValidation - .validateCapabilities(capabilityDefinitions, storedComponent, true); + .validateCapabilities(capabilityDefinitions, storedComponent, true); if (capabilitiesValidationEither.isRight()) { return Either.right(capabilitiesValidationEither.right().value()); } - Either lockResult = lockComponentResult(lock, storedComponent, errorContext); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); @@ -220,32 +203,30 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { if (Objects.isNull(capabilityDefinitionToGetType)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } - capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType - .getType(), storedComponentCapabilities); + capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType.getType(), + storedComponentCapabilities); } List capabilitiesDefListToUpdate = new ArrayList<>(); List capabilitiesToReturn = null; if (CollectionUtils.isNotEmpty(capabilitiesListStoredInComponent)) { - if (capabilityDefinitions.stream().anyMatch(capabilityDefinition -> - isCapabilityUsedInServiceComposition(capabilityDefinition, storedComponent))) { + if (capabilityDefinitions.stream() + .anyMatch(capabilityDefinition -> isCapabilityUsedInServiceComposition(capabilityDefinition, storedComponent))) { LOGGER.error("Capability can't be edited, since it is" + " used in service composition"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus. - CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION)); } for (CapabilityDefinition capabilityDefinitionToUpdate : capabilityDefinitions) { - capabilitiesToReturn = capabilitiesListStoredInComponent.stream().filter(capToUpdate -> - capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())) - .map(capabilityDefinition -> updateCapability(capabilityDefinition, - capabilityDefinitionToUpdate, storedComponent)).collect(Collectors.toList()); - capabilitiesListStoredInComponent.removeIf(capToUpdate -> capToUpdate.getUniqueId() - .equals(capabilityDefinitionToUpdate.getUniqueId())); + capabilitiesToReturn = capabilitiesListStoredInComponent.stream() + .filter(capToUpdate -> capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())) + .map(capabilityDefinition -> updateCapability(capabilityDefinition, capabilityDefinitionToUpdate, storedComponent)) + .collect(Collectors.toList()); + capabilitiesListStoredInComponent + .removeIf(capToUpdate -> capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())); if (CollectionUtils.isNotEmpty(capabilitiesToReturn)) { capabilitiesListStoredInComponent.addAll(capabilitiesToReturn); capabilitiesDefListToUpdate.addAll(capabilitiesListStoredInComponent); } else { - Either, ResponseFormat> capTypeUpdateEither - = handleCapabilityTypeUpdateWhenNewTypeExist(storedComponent, storedComponent - .getCapabilities(), capabilitiesToReturn, capabilityDefinitionToUpdate); + Either, ResponseFormat> capTypeUpdateEither = handleCapabilityTypeUpdateWhenNewTypeExist( + storedComponent, storedComponent.getCapabilities(), capabilitiesToReturn, capabilityDefinitionToUpdate); if (capTypeUpdateEither.isRight()) { return Either.right(capTypeUpdateEither.right().value()); } @@ -254,26 +235,23 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { } result = capabilitiesOperation.updateCapabilities(componentId, capabilitiesDefListToUpdate); } else { - Either, ResponseFormat> capabilityDefinitionToDelete - = handleCapabilityTypeUpdateWhenNewTypeNotExist(capabilityDefinitions, storedComponent, - storedComponentCapabilities); + Either, ResponseFormat> capabilityDefinitionToDelete = handleCapabilityTypeUpdateWhenNewTypeNotExist( + capabilityDefinitions, storedComponent, storedComponentCapabilities); if (capabilityDefinitionToDelete != null) { return capabilityDefinitionToDelete; } - capabilitiesToReturn = capabilityDefinitions.stream().map(capabilityDefinition -> - initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList()); + capabilitiesToReturn = capabilityDefinitions.stream() + .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList()); result = capabilitiesOperation.addCapabilities(componentId, capabilitiesToReturn); } if (result.isRight()) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result - .right().value(), storedComponent.getComponentType()), "")); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), "")); } - Map propertiesMap = - getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions); + Map propertiesMap = getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions); if (MapUtils.isNotEmpty(propertiesMap)) { - StorageOperationStatus storageOperationStatus = capabilitiesOperation - .createOrUpdateCapabilityProperties(componentId, propertiesMap); + StorageOperationStatus storageOperationStatus = capabilitiesOperation.createOrUpdateCapabilityProperties(componentId, propertiesMap); if (storageOperationStatus != StorageOperationStatus.OK) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(storageOperationStatus)); @@ -287,81 +265,67 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - private Either, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeExist( - Component storedComponent, - Map> storedComponentCapabilities, - List capabilitiesToReturn, - CapabilityDefinition capabilityDefinitionToUpdate) { - + private Either, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeExist(Component storedComponent, + Map> storedComponentCapabilities, + List capabilitiesToReturn, + CapabilityDefinition capabilityDefinitionToUpdate) { List capabilitiesListStoredInComponent; List capabilitiesDefsToCreateOrUpdate = new ArrayList<>(); - Optional definitionOptional = storedComponentCapabilities.values().stream() - .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId() - .equals(capabilityDefinitionToUpdate.getUniqueId())).findAny(); + Optional definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream) + .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())).findAny(); if (!definitionOptional.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, - storedComponent.getUniqueId())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId())); } CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get(); - - capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToUpdate.getType(), - storedComponentCapabilities); - Either, StorageOperationStatus> deleteCapabilityEither - = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDelete); + capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToUpdate.getType(), storedComponentCapabilities); + Either, StorageOperationStatus> deleteCapabilityEither = deleteCapability(storedComponent, + storedComponentCapabilities, capabilityDefinitionToDelete); if (deleteCapabilityEither.isRight()) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteCapabilityEither.right().value())); } StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation - .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete)); + .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete)); if (deleteStorageOperationStatus != StorageOperationStatus.OK) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteStorageOperationStatus)); } capabilitiesToReturn.add(initiateNewCapability(storedComponent, capabilityDefinitionToUpdate)); - capabilitiesDefsToCreateOrUpdate.addAll(capabilitiesToReturn); capabilitiesDefsToCreateOrUpdate.addAll(capabilitiesListStoredInComponent); return Either.left(capabilitiesDefsToCreateOrUpdate); } private Either, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeNotExist( - List capabilityDefinitions, - Component storedComponent, - Map> storedComponentCapabilities) { + List capabilityDefinitions, Component storedComponent, + Map> storedComponentCapabilities) { for (CapabilityDefinition capabilityDefinitionToUpdate : capabilityDefinitions) { - - Optional definitionOptional = storedComponentCapabilities.values().stream() - .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId() - .equals(capabilityDefinitionToUpdate.getUniqueId())).findAny(); + Optional definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream) + .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())).findAny(); if (!definitionOptional.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .CAPABILITY_NOT_FOUND, storedComponent.getUniqueId())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId())); } CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get(); - Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, - storedComponent); + Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent); if (isCapabilityUsedInServiceComposition) { - LOGGER.error("Capability {} can't be edited, since it is used in service composition", - capabilityDefinitionToDelete.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION, - capabilityDefinitionToDelete.getName())); + LOGGER.error("Capability {} can't be edited, since it is used in service composition", capabilityDefinitionToDelete.getUniqueId()); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName())); } - Either, StorageOperationStatus> deleteCapabilityEither - = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDelete); + Either, StorageOperationStatus> deleteCapabilityEither = deleteCapability(storedComponent, + storedComponentCapabilities, capabilityDefinitionToDelete); if (deleteCapabilityEither.isRight()) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteCapabilityEither.right().value())); } StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation - .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete)); + .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete)); if (deleteStorageOperationStatus != StorageOperationStatus.OK) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteStorageOperationStatus)); @@ -370,22 +334,19 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return null; } - public Either getCapability(String componentId, String capabilityToGet, - User user, boolean lock) { + public Either getCapability(String componentId, String capabilityToGet, User user, boolean lock) { validateUserExists(user.getUserId()); Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } Component storedComponent = componentEither.left().value(); - Either lockResult = lockComponentResult(lock, storedComponent, GET_CAPABILITIES); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } try { - Either getCapabilityDefinitionEither = - getCapabilityDefinition(capabilityToGet, storedComponent); + Either getCapabilityDefinitionEither = getCapabilityDefinition(capabilityToGet, storedComponent); if (getCapabilityDefinitionEither.isRight()) { return Either.right(getCapabilityDefinitionEither.right().value()); } @@ -395,42 +356,36 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, componentId)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - private Either getCapabilityDefinition(String capabilityIdToGet, - Component storedComponent) { - List capabilityDefinitions = storedComponent.getCapabilities().values() - .stream().flatMap(Collection::stream).collect(Collectors.toList()); + private Either getCapabilityDefinition(String capabilityIdToGet, Component storedComponent) { + List capabilityDefinitions = storedComponent.getCapabilities().values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); if (capabilityDefinitions.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, - storedComponent.getUniqueId())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId())); } CapabilityDefinition capabilityDefinitionToReturn; Optional capabilityDefinitionOptional = capabilityDefinitions.stream() - .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToGet)).findAny(); + .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToGet)).findAny(); if (capabilityDefinitionOptional.isPresent()) { capabilityDefinitionToReturn = capabilityDefinitionOptional.get(); } else { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, - storedComponent.getUniqueId())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId())); } - return Either.left(capabilityDefinitionToReturn); } - public Either deleteCapability(String componentId, String capabilityIdToDelete, - User user, boolean lock) { + public Either deleteCapability(String componentId, String capabilityIdToDelete, User user, boolean lock) { validateUserExists(user.getUserId()); Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } Component storedComponent = componentEither.left().value(); - Either lockResult = lockComponentResult(lock, storedComponent, DELETE_CAPABILITIES); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); @@ -443,85 +398,74 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - private Either deleteCapability(String capabilityIdToDelete, - Component storedComponent) { + private Either deleteCapability(String capabilityIdToDelete, Component storedComponent) { Map> storedComponentCapabilities = storedComponent.getCapabilities(); if (storedComponentCapabilities.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId())); } - Either capabilityDefinitionToDeleteEither = - getAndValidateCapabilitiesToDelete(storedComponent, storedComponentCapabilities, capabilityIdToDelete); - - if(capabilityDefinitionToDeleteEither.isRight()) { + Either capabilityDefinitionToDeleteEither = getAndValidateCapabilitiesToDelete(storedComponent, + storedComponentCapabilities, capabilityIdToDelete); + if (capabilityDefinitionToDeleteEither.isRight()) { return Either.right(capabilityDefinitionToDeleteEither.right().value()); } - Either, StorageOperationStatus> result = deleteCapability(storedComponent, - storedComponentCapabilities, capabilityDefinitionToDeleteEither.left().value()); + Either, StorageOperationStatus> result = deleteCapability(storedComponent, storedComponentCapabilities, + capabilityDefinitionToDeleteEither.left().value()); if (result.isRight()) { janusGraphDao.rollback(); - LOGGER.error("Failed to delete capability from component {}. Response is {}", storedComponent.getName(), - result.right().value()); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(result.right().value(), - storedComponent.getComponentType()))); + LOGGER.error("Failed to delete capability from component {}. Response is {}", storedComponent.getName(), result.right().value()); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()))); } janusGraphDao.commit(); - return Either.left(capabilityDefinitionToDeleteEither.left().value()); } private Either getAndValidateCapabilitiesToDelete(Component storedComponent, Map> storedComponentCapabilities, String capabilityIdToDelete) { - - Optional definitionOptional = storedComponentCapabilities.values().stream() - .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId() - .equals(capabilityIdToDelete)).findAny(); + Optional definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream) + .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToDelete)).findAny(); if (!definitionOptional.isPresent()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId())); } CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get(); - Boolean isCapabilityUsedInServiceComposition - = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent); + Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent); if (isCapabilityUsedInServiceComposition) { - LOGGER.error("Capability {} can't be deleted, since it is used in service composition", - capabilityDefinitionToDelete.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName())); + LOGGER.error("Capability {} can't be deleted, since it is used in service composition", capabilityDefinitionToDelete.getUniqueId()); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName())); } - return Either.left(capabilityDefinitionToDelete); } + private Either, StorageOperationStatus> deleteCapability(Component storedComponent, Map> storedComponentCapabilities, CapabilityDefinition capabilityDefinitionToDelete) { - - List capabilitiesListStoredInComponent = - getCapabilityStoredInComponentByType(capabilityDefinitionToDelete.getType(), storedComponentCapabilities); - capabilitiesListStoredInComponent.removeIf(capabilityDefinition -> - capabilityDefinition.getUniqueId().equals(capabilityDefinitionToDelete.getUniqueId())); + List capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToDelete.getType(), + storedComponentCapabilities); + capabilitiesListStoredInComponent + .removeIf(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToDelete.getUniqueId())); Either, StorageOperationStatus> result; if (capabilitiesListStoredInComponent.isEmpty()) { - StorageOperationStatus operationStatus = capabilitiesOperation.deleteCapabilities(storedComponent, - capabilityDefinitionToDelete.getType()); + StorageOperationStatus operationStatus = capabilitiesOperation + .deleteCapabilities(storedComponent, capabilityDefinitionToDelete.getType()); if (StorageOperationStatus.OK.equals(operationStatus)) { result = Either.left(Collections.singletonList(capabilityDefinitionToDelete)); } else { result = Either.right(operationStatus); } } else { - result = capabilitiesOperation.updateCapabilities(storedComponent.getUniqueId(), - capabilitiesListStoredInComponent); + result = capabilitiesOperation.updateCapabilities(storedComponent.getUniqueId(), capabilitiesListStoredInComponent); } if (result.isLeft()) { StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation - .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete)); + .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete)); if (deleteStorageOperationStatus != StorageOperationStatus.OK) { result = Either.right(deleteStorageOperationStatus); } @@ -529,17 +473,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return result; } - private Either getComponentDetails(String componentId) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreCapabilities(false); filter.setIgnoreCapabiltyProperties(false); - Either componentStorageOperationStatusEither = - toscaOperationFacade.getToscaElement(componentId, filter); + Either componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId, filter); if (componentStorageOperationStatusEither.isRight()) { StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value(); - LOGGER.error("Failed to fetch component information by component id {}, Response is {}", - componentId, errorStatus); + LOGGER.error("Failed to fetch component information by component id {}, Response is {}", componentId, errorStatus); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); } return Either.left(componentStorageOperationStatusEither.left().value()); @@ -549,7 +490,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { if (lock) { try { lockComponent(component.getUniqueId(), component, action); - } catch (ComponentException e){ + } catch (ComponentException e) { LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), e.getMessage()); janusGraphDao.rollback(); throw e; @@ -558,40 +499,41 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private List getCapabilityStoredInComponentByType(String capabilityType, Map> capabilities) { + private List getCapabilityStoredInComponentByType(String capabilityType, + Map> capabilities) { Optional>> entryOptional = capabilities.entrySet().stream() - .filter(map -> map.getKey().equals(capabilityType)).findFirst(); + .filter(map -> map.getKey().equals(capabilityType)).findFirst(); return entryOptional.map(Map.Entry::getValue).orElse(Collections.emptyList()); } private CapabilityDefinition initiateNewCapability(Component component, CapabilityDefinition capabilityDefinition) { - if (StringUtils.isEmpty(capabilityDefinition.getUniqueId())) + if (StringUtils.isEmpty(capabilityDefinition.getUniqueId())) { capabilityDefinition.setUniqueId(UUID.randomUUID().toString()); - if (StringUtils.isEmpty(capabilityDefinition.getOwnerId())) + } + if (StringUtils.isEmpty(capabilityDefinition.getOwnerId())) { capabilityDefinition.setOwnerId(component.getUniqueId()); - if (StringUtils.isEmpty(capabilityDefinition.getOwnerName())) + } + if (StringUtils.isEmpty(capabilityDefinition.getOwnerName())) { capabilityDefinition.setOwnerName(component.getName()); + } capabilityDefinition.setLeftOccurrences(capabilityDefinition.getMaxOccurrences()); List capabilityProperties = capabilityDefinition.getProperties(); initiateProperties(capabilityDefinition, capabilityProperties); return capabilityDefinition; } - private void initiateProperties(CapabilityDefinition capabilityDefinition, - List capabilityProperties) { + private void initiateProperties(CapabilityDefinition capabilityDefinition, List capabilityProperties) { if (CollectionUtils.isNotEmpty(capabilityProperties)) { - capabilityProperties.stream().filter(prop -> prop != null && StringUtils.isEmpty(prop.getUniqueId())) - .forEach(propDef -> { - String uid = UniqueIdBuilder.buildRequirementUid(capabilityDefinition.getUniqueId(), propDef.getName()); - propDef.setUniqueId(uid); - propDef.setParentUniqueId(capabilityDefinition.getUniqueId()); - }); + capabilityProperties.stream().filter(prop -> prop != null && StringUtils.isEmpty(prop.getUniqueId())).forEach(propDef -> { + String uid = UniqueIdBuilder.buildRequirementUid(capabilityDefinition.getUniqueId(), propDef.getName()); + propDef.setUniqueId(uid); + propDef.setParentUniqueId(capabilityDefinition.getUniqueId()); + }); } } - private CapabilityDefinition updateCapability(CapabilityDefinition storedCapability, - CapabilityDefinition capabilityToUpdate, Component component) { + private CapabilityDefinition updateCapability(CapabilityDefinition storedCapability, CapabilityDefinition capabilityToUpdate, + Component component) { storedCapability.setName(capabilityToUpdate.getName()); storedCapability.setDescription(capabilityToUpdate.getDescription()); storedCapability.setType(capabilityToUpdate.getType()); @@ -605,48 +547,44 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { } if (!storedCapability.getName().equals(capabilityToUpdate.getName())) { StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation - .deleteCapabilityProperties(component, buildCapPropKey(storedCapability)); + .deleteCapabilityProperties(component, buildCapPropKey(storedCapability)); if (deleteStorageOperationStatus != StorageOperationStatus.OK) { janusGraphDao.rollback(); } } - return storedCapability; } - private Boolean isCapabilityUsedInServiceComposition(CapabilityDefinition capabilityDefinition, Component component) { - Either, StorageOperationStatus> componentList = toscaOperationFacade - .getParentComponents(component.getUniqueId()); + Either, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId()); if (componentList.isRight()) { return Boolean.FALSE; } - return componentList.left().value().stream().flatMap(parentComponent -> parentComponent - .getComponentInstancesRelations().stream()).flatMap(requirementCapabilityRelDef -> - requirementCapabilityRelDef.getRelationships().stream()).anyMatch(capabilityRequirementRelationship -> - capabilityRequirementRelationship.getRelation().getCapabilityUid().equals(capabilityDefinition.getUniqueId())); + return componentList.left().value().stream().flatMap(parentComponent -> parentComponent.getComponentInstancesRelations().stream()) + .flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream()).anyMatch( + capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation().getCapabilityUid() + .equals(capabilityDefinition.getUniqueId())); } public Either, ResponseFormat> getAllCapabilityTypes() { - Either, JanusGraphOperationStatus> capabilityTypeCacheAll = - capabilityTypeOperation.getAllCapabilityTypes(); + Either, JanusGraphOperationStatus> capabilityTypeCacheAll = capabilityTypeOperation + .getAllCapabilityTypes(); if (capabilityTypeCacheAll.isRight()) { JanusGraphOperationStatus operationStatus = capabilityTypeCacheAll.right().value(); if (JanusGraphOperationStatus.NOT_FOUND == operationStatus) { - BeEcompErrorManager.getInstance().logInternalDataError("FetchCapabilityTypes", - "Capability types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInternalDataError("FetchCapabilityTypes", "Capability types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); } else { - BeEcompErrorManager.getInstance().logInternalFlowError("FetchCapabilityTypes", - "Failed to fetch capability types", BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInternalFlowError("FetchCapabilityTypes", "Failed to fetch capability types", BeEcompErrorManager.ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } } return Either.left(capabilityTypeCacheAll.left().value()); } - private Map getCapabilitiesPropertiesDataDefinitionMap( - List capabilityDefinitions) { + private Map getCapabilitiesPropertiesDataDefinitionMap(List capabilityDefinitions) { CapabilityDefinition capabilityDefinitionToAddOrUpdateCapProp = capabilityDefinitions.get(0); List componentInstanceProperties = null; if (Objects.nonNull(capabilityDefinitionToAddOrUpdateCapProp)) { @@ -664,7 +602,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic { } private String buildCapPropKey(CapabilityDefinition capabilityDefinitionToAddOrUpdateCapProp) { - return capabilityDefinitionToAddOrUpdateCapProp.getType() + ModelConverter.CAP_PROP_DELIM + - capabilityDefinitionToAddOrUpdateCapProp.getName(); + return capabilityDefinitionToAddOrUpdateCapProp.getType() + ModelConverter.CAP_PROP_DELIM + capabilityDefinitionToAddOrUpdateCapProp + .getName(); } } 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 ebe79f57f8..df7650f24a 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 @@ -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. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.List; +import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; @@ -33,9 +34,6 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Map; - @Component("capabilityTypeImportManager") public class CapabilityTypeImportManager { @@ -50,51 +48,44 @@ public class CapabilityTypeImportManager { } public Either>, ResponseFormat> createCapabilityTypes(String capabilityTypesYml) { - return commonImportManager.createElementTypes(capabilityTypesYml, this::createCapabilityTypesFromYml, this::upsertCapabilityTypesByDao, CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE); - + return commonImportManager.createElementTypes(capabilityTypesYml, this::createCapabilityTypesFromYml, this::upsertCapabilityTypesByDao, + CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE); } private Either, ActionStatus> createCapabilityTypesFromYml(String capabilityTypesYml) { return commonImportManager.createElementTypesFromYml(capabilityTypesYml, this::createCapabilityType); - } - private Either>, ResponseFormat> upsertCapabilityTypesByDao(List capabilityTypesToCreate) { - return commonImportManager.createElementTypesByDao(capabilityTypesToCreate, - capabilityType -> Either.left(ActionStatus.OK), - capabilityType -> new ImmutablePair<>(CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE, capabilityType.getType()), - capabilityTypeOperation::getCapabilityType, - capabilityTypeOperation::addCapabilityType, - this::updateCapabilityType); + private Either>, ResponseFormat> upsertCapabilityTypesByDao( + List capabilityTypesToCreate) { + return commonImportManager.createElementTypesByDao(capabilityTypesToCreate, capabilityType -> Either.left(ActionStatus.OK), + capabilityType -> new ImmutablePair<>(CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE, capabilityType.getType()), + capabilityTypeOperation::getCapabilityType, capabilityTypeOperation::addCapabilityType, this::updateCapabilityType); } - - private Either updateCapabilityType(CapabilityTypeDefinition newCapabilityType, CapabilityTypeDefinition oldCapabilityType) { + + private Either updateCapabilityType(CapabilityTypeDefinition newCapabilityType, + CapabilityTypeDefinition oldCapabilityType) { Either validationRes = capabilityTypeOperation.validateUpdateProperties(newCapabilityType); if (validationRes.isRight()) { - log.error("#updateCapabilityType - One or all properties of capability type {} not valid. status is {}", newCapabilityType, validationRes.right().value()); + log.error("#updateCapabilityType - One or all properties of capability type {} not valid. status is {}", newCapabilityType, + validationRes.right().value()); return validationRes; } - if (TypeCompareUtils.isCapabilityTypesEquals(newCapabilityType, oldCapabilityType)) { return TypeCompareUtils.typeAlreadyExists(); } - return capabilityTypeOperation.updateCapabilityType(newCapabilityType, oldCapabilityType); } private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map toscaJson) { CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); - capabilityType.setType(capabilityTypeName); - // Description commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), capabilityType::setDescription); // Derived From commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), capabilityType::setDerivedFrom); // Properties commonImportManager.setPropertiesMap(toscaJson, capabilityType::setProperties); - 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 fb85ab5326..6ebdb9bfab 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 @@ -24,15 +24,6 @@ package org.openecomp.sdc.be.components.impl; 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.log.wrappers.Logger; -import org.openecomp.sdc.common.util.GeneralUtility; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; @@ -42,40 +33,38 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +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.log.wrappers.Logger; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.springframework.stereotype.Component; @Component("cassandra-health-check") public class CassandraHealthCheck { private static final Logger log = Logger.getLogger(CassandraHealthCheck.class); - - private String localDataCenterName; - private final Set sdcKeyspaces = new HashSet<>(); - + private String localDataCenterName; private int HC_FormulaNumber; - private SdcSchemaUtils sdcSchemaUtils; @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)) { + 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 janusGraphCfgFile = ConfigurationManager.getConfigurationManager() - .getConfiguration().getJanusGraphCfgFile(); + String janusGraphCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphCfgFile(); Properties prop = new Properties(); - try (final InputStream janusGraphProp = new FileInputStream(janusGraphCfgFile)) { //load a properties file prop.load(janusGraphProp); @@ -87,34 +76,25 @@ public class CassandraHealthCheck { } catch (Exception e) { log.error("Failed to open janusGraph.properties file , url is : {}", janusGraphCfgFile, e); } - log.info("All sdc keyspaces are : {}", sdcKeyspaces); sdcSchemaUtils = new SdcSchemaUtils(); //Calculate the Formula of Health Check try { - log.info("creating cluster for Cassandra Health Check."); //Create cluster from nodes in cassandra configuration - Metadata metadata = sdcSchemaUtils.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()); + 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"))); @@ -125,61 +105,43 @@ public class CassandraHealthCheck { } } } - if (replactionFactorList.isEmpty()) { 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); } - } public boolean getCassandraStatus() { - if (GeneralUtility.isEmptyString(localDataCenterName)) { log.error("localDataCenter Name in configuration.yaml is missing."); return false; } - try (final Session session = sdcSchemaUtils.connect()) { log.info("creating cluster for Cassandra for monitoring."); - log.info("The cassandra session is {}", session); if (session == null) { log.error("Failed to connect to cassandra "); return false; } - Metadata metadata = sdcSchemaUtils.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(); - + 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; @@ -188,7 +150,7 @@ public class CassandraHealthCheck { @PreDestroy public void closeClient() { - if (sdcSchemaUtils!= null) { + if (sdcSchemaUtils != null) { sdcSchemaUtils.closeCluster(); } log.info("** sdcSchemaUtils cluster closed"); 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 754420dd47..1efb4b6b9c 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 @@ -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. @@ -17,12 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; 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 java.util.Map.Entry; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils; import org.openecomp.sdc.be.datatypes.category.MetadataKeyDataDefinition; @@ -41,27 +46,16 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; -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.Map.Entry; - @Component("categoriesImportManager") public class CategoriesImportManager { + private static final Logger log = Logger.getLogger(CategoriesImportManager.class.getName()); @javax.annotation.Resource private IElementOperation elementOperation; - @javax.annotation.Resource private ComponentsUtils componentsUtils; - private static final Logger log = Logger.getLogger(CategoriesImportManager.class.getName()); - public Either>, ResponseFormat> createCategories(String categoriesTypesYml) { - Map> allCategories = createCategoriesFromYml(categoriesTypesYml); return createCategoriesByDao(allCategories); } @@ -74,21 +68,21 @@ public class CategoriesImportManager { 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); + log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, + nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup); List newCategoriesvalue = new ArrayList<>(); for (CategoryDefinition category : entry.getValue()) { - Either createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory); if (createdCategoryRes.isRight()) { return Either.right(createdCategoryRes.right().value()); } - CategoryDefinition newcategory = createdCategoryRes.left().value(); log.debug("createCategoriesByDao: create category was successful {}", newcategory); List newsubcategories = new ArrayList<>(); List subcategories = category.getSubcategories(); if (subcategories != null) { - boolean createdNewSubCategory = isCreatedNewSubCategory(entry, nodeTypeSubCategory, nodeTypeGroup, category, newcategory, newsubcategories, subcategories); + boolean createdNewSubCategory = isCreatedNewSubCategory(entry, nodeTypeSubCategory, nodeTypeGroup, category, newcategory, + newsubcategories, subcategories); if (!createdNewSubCategory) { return Either.right(createdCategoryRes.right().value()); } @@ -101,9 +95,12 @@ public class CategoriesImportManager { return Either.left(result); } - private boolean isCreatedNewSubCategory(Entry> entry, NodeTypeEnum nodeTypeSubCategory, NodeTypeEnum nodeTypeGroup, CategoryDefinition category, CategoryDefinition newcategory, List newsubcategories, List subcategories) { + private boolean isCreatedNewSubCategory(Entry> entry, NodeTypeEnum nodeTypeSubCategory, + NodeTypeEnum nodeTypeGroup, CategoryDefinition category, CategoryDefinition newcategory, + List newsubcategories, List subcategories) { for (SubCategoryDefinition subcategory : subcategories) { - Either createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory); + Either createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, + nodeTypeSubCategory); if (createdSubCategory.isRight()) { return false; } @@ -112,7 +109,8 @@ public class CategoriesImportManager { if (groupings != null) { List newgroupings = new ArrayList<>(); for (GroupingDefinition grouping : groupings) { - Either createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup); + Either createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, + nodeTypeGroup); if (createdGrouping.isRight()) { return false; } @@ -125,10 +123,12 @@ public class CategoriesImportManager { return true; } - private Either createGroupingDeo(Map.Entry> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) { - + 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); + Either createdGrouping = elementOperation + .createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup); if (createdGrouping.isRight()) { if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY == createdGrouping.right().value()) { log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName()); @@ -139,28 +139,31 @@ public class CategoriesImportManager { 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); - + 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 createSubCategorieDeo(Map.Entry> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) { + 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); + Either createdSubCategory = elementOperation + .createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory); if (createdSubCategory.isRight() && ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY == createdSubCategory.right().value()) { - log.debug(" create subcategory for {} category {} subcategory {} already exists, updating", entry.getKey(), newcategory.getName(), subcategory.getName()); + log.debug(" create subcategory for {} category {} subcategory {} already exists, updating", entry.getKey(), newcategory.getName(), + subcategory.getName()); String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName()); createdSubCategory = elementOperation.updateSubCategory(subCategoryId, subcategory, nodeTypeSubCategory); } if (createdSubCategory.isRight()) { - log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value()); + 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()); @@ -168,14 +171,14 @@ public class CategoriesImportManager { return Either.left(createdSubCategory.left().value()); } - private Either createCategorieDeo(Map.Entry> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) { + 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() && ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS == createdCategory.right().value()) { log.debug("createCategorieDeo: already exists, updating {}", category); createdCategory = elementOperation.updateCategory(category, nodeTypeCategory); } - if (createdCategory.isRight()) { log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value()); return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); @@ -188,7 +191,6 @@ public class CategoriesImportManager { private Map> createCategoriesFromYml(String categoriesTypesYml) { Map toscaJson = (Map) new Yaml().load(categoriesTypesYml); Map> allCategories = new HashMap<>(); - Iterator> categoryEntryItr = toscaJson.entrySet().iterator(); while (categoryEntryItr.hasNext()) { Entry categoryTypeEntry = categoryEntryItr.next(); @@ -196,20 +198,20 @@ public class CategoriesImportManager { 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; + 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); @@ -232,18 +234,18 @@ public class CategoriesImportManager { String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); catDef.setNormalizedName(normalizedName); final Object useServiceSubstitutionForNestedServicesProperty = category.get("useServiceSubstitutionForNestedServices"); - final boolean useServiceSubstitutionForNestedServices = useServiceSubstitutionForNestedServicesProperty == null ? - false : (Boolean) useServiceSubstitutionForNestedServicesProperty; + final boolean useServiceSubstitutionForNestedServices = + useServiceSubstitutionForNestedServicesProperty == null ? false : (Boolean) useServiceSubstitutionForNestedServicesProperty; catDef.setUseServiceSubstitutionForNestedServices(useServiceSubstitutionForNestedServices); catDef.setMetadataKeys(getMetadataKeys(category)); categoriesDef.add(catDef); } - return categoriesDef; } - + private List getMetadataKeys(Map parentObject) { - Map metadataKeys = (Map) parentObject.getOrDefault(MetadataKeyEnum.METADATA_KEYS.getName(), Collections.EMPTY_MAP); + Map metadataKeys = (Map) parentObject + .getOrDefault(MetadataKeyEnum.METADATA_KEYS.getName(), Collections.EMPTY_MAP); List metadataKeyDefs = new ArrayList<>(); for (Entry metadataKey : metadataKeys.entrySet()) { Map metadataKeyInfo = (Map) metadataKey.getValue(); @@ -284,7 +286,6 @@ public class CategoriesImportManager { subDef.setMetadataKeys(getMetadataKeys(subcategoryInfo)); subcateDef.add(subDef); } - catDef.setSubcategories(subcateDef); categroiesDef.add(catDef); } 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 c3ecda3e03..326022d806 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 @@ -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. @@ -19,10 +19,21 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; +import static java.util.stream.Collectors.toList; + 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; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; @@ -47,24 +58,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; -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 java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static java.util.stream.Collectors.toList; - @Component("commonImportManager") public class CommonImportManager { private static final Logger log = Logger.getLogger(CommonImportManager.class.getName()); - private final ComponentsUtils componentsUtils; private final PropertyOperation propertyOperation; @@ -81,12 +78,10 @@ public class CommonImportManager { private static 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()) { - for (Entry entry : propertiesMap.entrySet()) { String propName = entry.getKey(); PropertyDefinition propertyDefinition = entry.getValue(); @@ -96,28 +91,27 @@ public class CommonImportManager { } } } - return values; } + private static List append(List list, T value) { + list.add(value); + return list; + } + protected void setPropertiesMap(Map toscaJson, Consumer> consumer) { final List properties = getProperties(toscaJson); if (properties != null) { - Map collect = properties.stream() - .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); + Map collect = properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); consumer.accept(collect); } } - public interface ICreateElementType { - T3 createElement(T1 firstArg, T2 secondArg); - } - - protected Either, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType, T> createApi) { - + protected Either, ActionStatus> createElementTypesFromYml(String elementTypesYml, + ICreateElementType, T> createApi) { List elementTypes; Map toscaJson = convertToFieldMap(elementTypesYml); - if (toscaJson==null) { + if (toscaJson == null) { return Either.right(ActionStatus.INVALID_YAML_FILE); } elementTypes = createElementTypesFromToscaJsonMap(createApi, toscaJson); @@ -135,11 +129,9 @@ public class CommonImportManager { return toscaJson; } - - protected List createTypesFromToscaJsonMap( - BiFunction, T> createApi, Map toscaJson) { + protected List createTypesFromToscaJsonMap(BiFunction, T> createApi, + Map toscaJson) { List elementTypes = new ArrayList<>(); - for (Entry elementTypeNameDataEntry : toscaJson.entrySet()) { String elementTypeName = elementTypeNameDataEntry.getKey(); Map elementTypeJsonData = (Map) elementTypeNameDataEntry.getValue(); @@ -149,10 +141,9 @@ public class CommonImportManager { return elementTypes; } - protected List createElementTypesFromToscaJsonMap( - ICreateElementType, T> createApi, Map toscaJson) { + protected List createElementTypesFromToscaJsonMap(ICreateElementType, T> createApi, + Map toscaJson) { List elementTypes = new ArrayList<>(); - for (Entry elementTypeNameDataEntry : toscaJson.entrySet()) { String elementTypeName = elementTypeNameDataEntry.getKey(); Map elementTypeJsonData = (Map) elementTypeNameDataEntry.getValue(); @@ -162,10 +153,9 @@ public class CommonImportManager { return elementTypes; } - protected Map createElementTypesMapFromToscaJsonMap( - ICreateElementType, T> createApi, Map toscaJson) { + protected Map createElementTypesMapFromToscaJsonMap(ICreateElementType, T> createApi, + Map toscaJson) { Map elementTypesMap = new HashMap<>(); - Iterator> elementTypesEntryItr = toscaJson.entrySet().iterator(); while (elementTypesEntryItr.hasNext()) { Entry elementTypeNameDataEntry = elementTypesEntryItr.next(); @@ -184,31 +174,27 @@ public class CommonImportManager { } } - public enum ElementTypeEnum { - POLICY_TYPE, GROUP_TYPE, DATA_TYPE, CAPABILITY_TYPE, INTERFACE_LIFECYCLE_TYPE, RELATIONSHIP_TYPE - } - private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) { ActionStatus ret; switch (elementTypeEnum) { - case GROUP_TYPE: - ret = componentsUtils.convertFromStorageResponseForGroupType(status); - break; - case DATA_TYPE: - ret = componentsUtils.convertFromStorageResponseForDataType(status); - break; - case CAPABILITY_TYPE: - ret = componentsUtils.convertFromStorageResponseForCapabilityType(status); - break; - case INTERFACE_LIFECYCLE_TYPE: - ret = componentsUtils.convertFromStorageResponseForLifecycleType(status); - break; - case RELATIONSHIP_TYPE: - ret = componentsUtils.convertFromStorageResponseForRelationshipType(status); - break; - default: - ret = componentsUtils.convertFromStorageResponse(status); - break; + case GROUP_TYPE: + ret = componentsUtils.convertFromStorageResponseForGroupType(status); + break; + case DATA_TYPE: + ret = componentsUtils.convertFromStorageResponseForDataType(status); + break; + case CAPABILITY_TYPE: + ret = componentsUtils.convertFromStorageResponseForCapabilityType(status); + break; + case INTERFACE_LIFECYCLE_TYPE: + ret = componentsUtils.convertFromStorageResponseForLifecycleType(status); + break; + case RELATIONSHIP_TYPE: + ret = componentsUtils.convertFromStorageResponseForRelationshipType(status); + break; + default: + ret = componentsUtils.convertFromStorageResponse(status); + break; } return ret; } @@ -216,22 +202,21 @@ public class CommonImportManager { private ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, T elementTypeDefinition) { ResponseFormat ret; switch (elementTypeEnum) { - case GROUP_TYPE: - ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition); - break; - case POLICY_TYPE: - ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition); - break; - case DATA_TYPE: - ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null); - break; - case CAPABILITY_TYPE: - ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition); - break; - - default: - ret = componentsUtils.getResponseFormat(actionStatus); - break; + case GROUP_TYPE: + ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition); + break; + case POLICY_TYPE: + ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition); + break; + case DATA_TYPE: + ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null); + break; + case CAPABILITY_TYPE: + ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition); + break; + default: + ret = componentsUtils.getResponseFormat(actionStatus); + break; } return ret; } @@ -264,11 +249,13 @@ public class CommonImportManager { } return createdElementTypes; } - + protected Either>, ResponseFormat> createElementTypesByDao(List elementTypesToCreate, - Function> validator, Function> elementInfoGetter, - Function> elementFetcher, Function> elementAdder, - BiFunction> elementUpgrader) { + Function> validator, + Function> elementInfoGetter, + Function> elementFetcher, + Function> elementAdder, + BiFunction> elementUpgrader) { List> createdElementTypes = new ArrayList<>(); @@ -279,49 +266,42 @@ public class CommonImportManager { while (elementTypeItr.hasNext()) { T elementType = elementTypeItr.next(); eitherResult = handleType(elementType, validator, elementInfoGetter, elementFetcher, elementAdder, elementUpgrader) - .left() - .map(elem -> append(createdElementTypes, elem)); - + .left() + .map(elem -> append(createdElementTypes, elem)); + if (eitherResult.isRight()) { break; } - - if(!elementTypeItr.hasNext()) { + + if (!elementTypeItr.hasNext()) { log.info("all {} were created successfully!!!", elementType); } } - } - catch(Exception e) { + } catch (Exception e) { eitherResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); throw e; - } - finally { + } finally { if (eitherResult.isLeft()) { propertyOperation.getJanusGraphGenericDao().commit(); - } - else { + } else { propertyOperation.getJanusGraphGenericDao().rollback(); } } return eitherResult; } - - private static List append(List list, T value) { - list.add(value); - return list; - } - - - private Either, ResponseFormat> handleType(T elementType, - Function> validator, Function> elementInfoGetter, - Function> elementFetcher, Function> elementAdder, - BiFunction> elementUpgrader) { - + + private Either, ResponseFormat> handleType(T elementType, + Function> validator, + Function> elementInfoGetter, + Function> elementFetcher, + Function> elementAdder, + BiFunction> elementUpgrader) { + 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(); @@ -336,7 +316,8 @@ public class CommonImportManager { StorageOperationStatus status = findElementType.right().value(); log.debug("searched {} finished with result:{}", elementTypeEnum, status); if (status != StorageOperationStatus.NOT_FOUND) { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType); + ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), + elementTypeEnum, elementType); return Either.right(responseFormat); } else { return addElementType(elementType, elementAdder, elementTypeEnum, elementName); @@ -356,15 +337,18 @@ public class CommonImportManager { } } - private Either, ResponseFormat> addElementType(T elementType, Function> elementAdder, ElementTypeEnum elementTypeEnum, String elementName) { + private Either, ResponseFormat> addElementType(T elementType, + Function> elementAdder, + ElementTypeEnum elementTypeEnum, String elementName) { Either dataModelResponse = elementAdder.apply(elementType); - + if (dataModelResponse.isRight()) { BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name()); log.debug("failed to create {}: {}", elementTypeEnum, elementName); if (dataModelResponse.right().value() != StorageOperationStatus.OK) { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); - + ResponseFormat responseFormat = getResponseFormatForElementType( + convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); + return Either.right(responseFormat); } else { return Either.left(new ImmutablePair<>(elementType, false)); @@ -374,17 +358,19 @@ public class CommonImportManager { return Either.left(new ImmutablePair<>(elementType, true)); } } - - - private Either, ResponseFormat> updateElementType(T elementType, BiFunction> elementUpgrader, - ElementTypeEnum elementTypeEnum, String elementName, T existingElementType) { + + private Either, ResponseFormat> updateElementType(T elementType, + BiFunction> elementUpgrader, + ElementTypeEnum elementTypeEnum, String elementName, + T existingElementType) { Either upgradeResponse = elementUpgrader.apply(elementType, existingElementType); if (upgradeResponse.isRight()) { StorageOperationStatus status = upgradeResponse.right().value(); if (status == StorageOperationStatus.OK) { return Either.left(new ImmutablePair<>(elementType, false)); } else { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); + ResponseFormat responseFormat = getResponseFormatForElementType( + convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); return Either.right(responseFormat); } } else { @@ -393,34 +379,35 @@ public class CommonImportManager { } } - - public Either>, ResponseFormat> createElementTypes(ToscaTypeImportData toscaTypeImportData, Function, ActionStatus>> elementTypeFromYmlCreater, - Function, Either>, ResponseFormat>> elementTypeDaoCreater) { + public Either>, ResponseFormat> createElementTypes( + ToscaTypeImportData toscaTypeImportData, Function, ActionStatus>> elementTypeFromYmlCreater, + Function, Either>, ResponseFormat>> elementTypeDaoCreater) { Either, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(toscaTypeImportData.getToscaTypesYml()); return elementTypes - .right() - .map(err -> componentsUtils.getResponseFormat(err, "")) - .left() - .map(toscaTypes -> enrichTypesWithNonToscaMetadata(toscaTypes, toscaTypeImportData.getToscaTypeMetadata())) - .left() - .bind(elementTypeDaoCreater::apply); + .right() + .map(err -> componentsUtils.getResponseFormat(err, "")) + .left() + .map(toscaTypes -> enrichTypesWithNonToscaMetadata(toscaTypes, toscaTypeImportData.getToscaTypeMetadata())) + .left() + .bind(elementTypeDaoCreater::apply); } public List> createElementTypes(String toscaTypesYml, BiFunction, T> createApi, TypeOperations typeOperations) { Map fieldMap = convertToFieldMap(toscaTypesYml); - if (fieldMap==null) { + if (fieldMap == null) { throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML_FILE); } List elementTypes = createTypesFromToscaJsonMap(createApi, fieldMap); return createTypesByDao(elementTypes, typeOperations); } - private List enrichTypesWithNonToscaMetadata(List toscaTypes, Map toscaTypeMetadata) { + private List enrichTypesWithNonToscaMetadata(List toscaTypes, + Map toscaTypeMetadata) { return toscaTypes.stream() - .map(toscaType -> setNonToscaMetaDataOnType(toscaTypeMetadata, toscaType)) - .collect(toList()); + .map(toscaType -> setNonToscaMetaDataOnType(toscaTypeMetadata, toscaType)) + .collect(toList()); } private T setNonToscaMetaDataOnType(Map toscaTypeMetadata, T toscaTypeDefinition) { @@ -435,8 +422,10 @@ public class CommonImportManager { return toscaTypeDefinition; } - public Either>, ResponseFormat> createElementTypes(String elementTypesYml, Function, ActionStatus>> elementTypeFromYmlCreater, - Function, Either>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) { + public Either>, ResponseFormat> createElementTypes(String elementTypesYml, + Function, ActionStatus>> elementTypeFromYmlCreater, + Function, Either>, ResponseFormat>> elementTypeDaoCreater, + ElementTypeEnum elementTypeEnum) { Either, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml); if (elementTypes.isRight()) { @@ -447,4 +436,13 @@ public class CommonImportManager { return elementTypeDaoCreater.apply(elementTypes.left().value()); } + + public enum ElementTypeEnum { + POLICY_TYPE, GROUP_TYPE, DATA_TYPE, CAPABILITY_TYPE, INTERFACE_LIFECYCLE_TYPE, RELATIONSHIP_TYPE + } + + public interface ICreateElementType { + + T3 createElement(T1 firstArg, T2 secondArg); + } } 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 efab8592c1..9ce54c2cc8 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 @@ -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. @@ -19,13 +19,18 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; 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.function.BiFunction; import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -96,51 +101,31 @@ 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.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - public abstract class ComponentBusinessLogic extends BaseBusinessLogic { - protected ArtifactsBusinessLogic artifactsBusinessLogic; - + private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName()); protected final GroupBusinessLogic groupBusinessLogic; - + protected ArtifactsBusinessLogic artifactsBusinessLogic; protected GenericTypeBusinessLogic genericTypeBusinessLogic; - protected ComponentDescriptionValidator componentDescriptionValidator; protected ComponentProjectCodeValidator componentProjectCodeValidator; - protected CatalogOperation catalogOperations; protected ComponentIconValidator componentIconValidator; - protected ComponentValidator componentValidator; protected ComponentTagsValidator componentTagsValidator; protected ComponentNameValidator componentNameValidator; protected ComponentContactIdValidator componentContactIdValidator; - public ComponentBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsBusinessLogic artifactsBusinessLogic, - ArtifactsOperations artifactToscaOperation, - ComponentContactIdValidator componentContactIdValidator, - ComponentNameValidator componentNameValidator, - ComponentTagsValidator componentTagsValidator, - ComponentValidator componentValidator, - ComponentIconValidator componentIconValidator, - ComponentProjectCodeValidator componentProjectCodeValidator, - ComponentDescriptionValidator componentDescriptionValidator){ - - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public ComponentBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsBusinessLogic artifactsBusinessLogic, ArtifactsOperations artifactToscaOperation, + ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentDescriptionValidator componentDescriptionValidator) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.artifactsBusinessLogic = artifactsBusinessLogic; this.groupBusinessLogic = groupBusinessLogic; this.componentContactIdValidator = componentContactIdValidator; @@ -152,6 +137,33 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { this.componentDescriptionValidator = componentDescriptionValidator; } + private static Either saveToscaArtifactAndPopulateToscaArtifactsWithResult(Component component, + final ComponentsUtils componentsUtils, + final ArtifactTypeEnum artifactEnum, + final BiFunction> saveToscaArtifactPayloadFunction) { + ArtifactDefinition artifactDefinition = getToscaArtifactByTypeOrThrowException(component, artifactEnum, componentsUtils); + Either result = saveToscaArtifactPayloadFunction.apply(component, artifactDefinition); + if (result.isLeft()) { + ArtifactDefinition def = result.left().value(); + component.getToscaArtifacts().put(def.getArtifactLabel(), def); + } + return result; + } + + private static Optional getToscaArtifactByType(final Map toscaArtifacts, + final ArtifactTypeEnum typeEnum) { + return toscaArtifacts.values().stream().filter(p -> p.getArtifactType().equals(typeEnum.getType())).findAny(); + } + + private static ArtifactDefinition getToscaArtifactByTypeOrThrowException(final Component component, final ArtifactTypeEnum typeEnum, + final ComponentsUtils componentsUtils) { + return Optional.ofNullable(component.getToscaArtifacts()).flatMap(toscaArtifacts -> getToscaArtifactByType(toscaArtifacts, typeEnum)) + .orElseThrow(() -> { + log.debug("Impossible to find a ToscaArtifact with type '{}' for {}", typeEnum.getType(), component); + return new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, typeEnum.name())); + }); + } + public void setComponentDescriptionValidator(ComponentDescriptionValidator componentDescriptionValidator) { this.componentDescriptionValidator = componentDescriptionValidator; } @@ -176,27 +188,25 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { this.componentNameValidator = componentNameValidator; } - @Autowired public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) { this.genericTypeBusinessLogic = genericTypeBusinessLogic; } - private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName()); - public abstract Either, ResponseFormat> deleteMarkedComponents(); public abstract ComponentInstanceBusinessLogic getComponentInstanceBL(); - public abstract Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId); + public abstract Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, + String userId); /** - * * @param componentId * @param dataParamsToReturn * @return */ - public abstract Either getUiComponentDataTransferByComponentId(String componentId, List dataParamsToReturn); + public abstract Either getUiComponentDataTransferByComponentId(String componentId, + List dataParamsToReturn); User validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) { User validatedUser; @@ -204,14 +214,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { try { validateUserNotEmpty(user, ecompErrorContext); validatedUser = validateUserExists(user); - } catch(ByActionStatusComponentException e){ - if(e.getActionStatus() == ActionStatus.MISSING_INFORMATION){ + } catch (ByActionStatusComponentException e) { + if (e.getActionStatus() == ActionStatus.MISSING_INFORMATION) { user.setUserId("UNKNOWN"); } responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType()); throw e; - } catch(ByResponseFormatComponentException e){ + } catch (ByResponseFormatComponentException e) { responseFormat = e.getResponseFormat(); componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType()); throw e; @@ -226,69 +236,64 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } try { validateUserRole(user, roles); - }catch (ByActionStatusComponentException e) { + } catch (ByActionStatusComponentException e) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); handleComponentException(component, comment, responseFormat, user, auditAction); throw e; - }catch (ByResponseFormatComponentException e) { + } catch (ByResponseFormatComponentException e) { ResponseFormat responseFormat = e.getResponseFormat(); handleComponentException(component, comment, responseFormat, user, auditAction); throw e; } } - private void handleComponentException(Component component, String comment, ResponseFormat responseFormat, - User user, AuditingActionEnum auditAction){ + private void handleComponentException(Component component, String comment, ResponseFormat responseFormat, User user, + AuditingActionEnum auditAction) { String commentStr = null; String distrStatus = null; ComponentTypeEnum componentType = component.getComponentType(); - if (componentType == ComponentTypeEnum.SERVICE) { - distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus(); + if (componentType == ComponentTypeEnum.SERVICE) { + distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()) + .getDistributionStatus(); commentStr = comment; } componentsUtils.auditComponent(responseFormat, user, component, auditAction, new ResourceCommonInfo(componentType.getValue()), ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(), - ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(), - commentStr, null, null); + ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(), commentStr, null, null); } 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); } - validateUserExists(userId); - - Either eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null); + 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); + 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); } @@ -304,9 +309,9 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } try { validateIcon(icon, type); - } catch(ComponentException e){ - ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() - : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); + } catch (ComponentException e) { + ResponseFormat responseFormat = + e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); throw e; } @@ -318,7 +323,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { log.debug("icon exceeds max length"); throw new ComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); } - if (!ValidationUtils.validateIcon(icon)) { log.info("icon is invalid."); throw new ComponentException(ActionStatus.COMPONENT_INVALID_ICON, type.getValue()); @@ -377,67 +381,70 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { log.debug("validate icon"); validateIcon(user, component, actionEnum); } - - public CapReqDef getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { + public CapReqDef getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { validateUserExists(userId); ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreCapabilities(false); filter.setIgnoreRequirements(false); filter.setIgnoreComponentInstances(false); - try { Component component = validateComponentExists(componentId, componentTypeEnum, filter); return new CapReqDef(component.getRequirements(), component.getCapabilities()); - }catch (ComponentException e){ + } catch (ComponentException e) { BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId); throwComponentException(e.getResponseFormat()); } return null; } - public Either, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids, + public Either, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, + ComponentTypeEnum componentTypeEnum, + String internalComponentType, List componentUids, String userId) { - try{ + try { validateUserExists(userId); 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()); - Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, componentTypeEnum, internalComponentType, componentsUidToFetch); - + Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade + .getLatestVersionNotAbstractComponents(isAbstractAbstract, componentTypeEnum, internalComponentType, componentsUidToFetch); if (nonCheckoutCompResponse.isLeft()) { log.debug("Retrived Resource successfully."); result.addAll(nonCheckoutCompResponse.left().value()); } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()))); + return Either.right( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()))); } } return Either.left(result); - } - finally{ + } finally { janusGraphDao.commit(); } } - public Either, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) { - try{ + public Either, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, + HighestFilterEnum highestFilter, + ComponentTypeEnum componentTypeEnum, + String internalComponentType, String userId) { + try { validateUserExists(userId); - Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType); - + Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade + .getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType); if (nonCheckoutCompResponse.isLeft()) { log.debug("Retrieved Resource successfully."); return Either.left(nonCheckoutCompResponse.left().value()); } - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()))); + return Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()))); } finally { janusGraphDao.commit(); } } public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - } @SuppressWarnings("unchecked") @@ -450,141 +457,101 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { 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"))); + 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 populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) { + public Either populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, + boolean inTransaction, boolean shouldLock) { return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, true); } - public Either populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean retrieveResource) { + public Either populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, + boolean inTransaction, boolean shouldLock, boolean retrieveResource) { return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, retrieveResource); } - private Either populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB, boolean retrieveResource) { + private Either populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, + boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB, + boolean retrieveResource) { if (retrieveResource) { Either toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId()); - if ( toscaElement.isRight() ){ - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); + if (toscaElement.isRight()) { + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); } component = toscaElement.left().value(); } - - Either generateToscaRes = - saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils, - ArtifactTypeEnum.TOSCA_TEMPLATE, - (comp, toscaArtifact) -> - saveToscaArtifactPayload(toscaArtifact, comp, user, isInCertificationRequest, shouldLock, - inTransaction, fetchTemplatesFromDB)); - + Either generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils, + ArtifactTypeEnum.TOSCA_TEMPLATE, + (comp, toscaArtifact) -> saveToscaArtifactPayload(toscaArtifact, comp, user, isInCertificationRequest, shouldLock, inTransaction, + fetchTemplatesFromDB)); if (!isAbstractResource(component)) { - generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils, - ArtifactTypeEnum.TOSCA_CSAR, - (comp, toscaArtifactArg) -> saveToscaArtifactPayload(toscaArtifactArg, comp, user, - isInCertificationRequest, shouldLock, inTransaction, true)); + generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils, ArtifactTypeEnum.TOSCA_CSAR, + (comp, toscaArtifactArg) -> saveToscaArtifactPayload(toscaArtifactArg, comp, user, isInCertificationRequest, shouldLock, + inTransaction, true)); } return generateToscaRes; } - private static Either saveToscaArtifactAndPopulateToscaArtifactsWithResult( - Component component, - final ComponentsUtils componentsUtils, - final ArtifactTypeEnum artifactEnum, - final BiFunction> saveToscaArtifactPayloadFunction) { - - ArtifactDefinition artifactDefinition = getToscaArtifactByTypeOrThrowException(component, artifactEnum, - componentsUtils); - - Either result = - saveToscaArtifactPayloadFunction.apply(component, artifactDefinition); - - if (result.isLeft()) { - ArtifactDefinition def = result.left().value(); - component.getToscaArtifacts().put(def.getArtifactLabel(), def); - } - - return result; - } - - private static Optional getToscaArtifactByType( - final Map toscaArtifacts, - final ArtifactTypeEnum typeEnum) { - return toscaArtifacts.values().stream() - .filter(p -> p.getArtifactType().equals(typeEnum.getType())) - .findAny(); - } - - private static ArtifactDefinition getToscaArtifactByTypeOrThrowException( - final Component component, - final ArtifactTypeEnum typeEnum, - final ComponentsUtils componentsUtils) { - - return Optional.ofNullable(component.getToscaArtifacts()) - .flatMap(toscaArtifacts -> getToscaArtifactByType(toscaArtifacts, typeEnum)) - .orElseThrow(() -> { - log.debug("Impossible to find a ToscaArtifact with type '{}' for {}", typeEnum.getType(), component); - return new ByResponseFormatComponentException( - componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, typeEnum.name())); - }); - } - private boolean isAbstractResource(Component component) { - return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract(); + return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).isAbstract(); } - private Either 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); + private Either 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 ImmutablePair getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, ResourceCommonInfo resourceCommonInfo) { - + public ImmutablePair getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, + ResourceCommonInfo resourceCommonInfo) { Either, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null); - if (latestVersionEither.isRight()) { - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); } - List components = latestVersionEither.left().value(); - Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null); - if(component == null){ + if (component == null) { component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null); } - - if(component == null){ - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType))); + if (component == null) { + throw new ByResponseFormatComponentException( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType))); } resourceCommonInfo.setResourceName(component.getName()); // TODO remove after migration - handle artifact not found(no + // placeholder) if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name())); + throw new ByResponseFormatComponentException( + 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(); + .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); @@ -596,7 +563,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } } - public Either validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) { + 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)) { @@ -621,7 +589,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - public Either validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) { + 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)) { @@ -630,7 +599,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { 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()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", + currentComponent.getComponentType().name().toLowerCase()); return Either.right(errorResponse); } } @@ -638,14 +608,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } protected Either, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) { - log.trace("start deleteMarkedComponents"); Either, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType); - - - if ( deleteMarkedElements.isRight()){ + if (deleteMarkedElements.isRight()) { janusGraphDao.rollback(); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); return Either.right(responseFormat); } log.trace("end deleteMarkedComponents"); @@ -668,32 +636,27 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } /** - * * @param componentId * @param user * @param dataParamsToReturn - ui list of params to return * @return */ - - public Either getComponentDataFilteredByParams(String componentId, User user, List dataParamsToReturn) { - + public Either getComponentDataFilteredByParams(String componentId, User user, + List dataParamsToReturn) { if (user != null) { validateUserExists(user); } - - UiComponentDataTransfer result = new UiComponentDataTransfer(); - - if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) { + UiComponentDataTransfer result = new UiComponentDataTransfer(); + if (dataParamsToReturn == null || dataParamsToReturn.isEmpty()) { Either.left(result); - } else { - Either uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn); - if(uiDataTransferEither.isRight()){ + Either uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, + dataParamsToReturn); + if (uiDataTransferEither.isRight()) { return Either.right(uiDataTransferEither.right().value()); } result = uiDataTransferEither.left().value(); } - return Either.left(result); } @@ -701,7 +664,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { List genericAndComponentInputs = new ArrayList<>(); List genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType); genericAndComponentInputs.addAll(genericInputs); - if (null != component.getInputs()){ + if (null != component.getInputs()) { List nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs()); genericAndComponentInputs.addAll(nonGenericInputsFromComponent); } @@ -712,7 +675,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { if (genericInputs == null) { return componentInputs; } - Map inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName); List componentNonGenericInputs = new ArrayList<>(); componentInputs.stream().forEach(input -> { @@ -723,9 +685,9 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return componentNonGenericInputs; } - protected Resource fetchAndSetDerivedFromGenericType(T component){ + protected Resource fetchAndSetDerivedFromGenericType(T component) { Either genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component); - if(genericTypeEither.isRight()){ + if (genericTypeEither.isRight()) { log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType()); throw new ByActionStatusComponentException(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType()); } @@ -734,30 +696,33 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return genericTypeResource; } - public Either>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map> filters, String userId) { + 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))){ + 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) { validateUserExists(userId); } - if(response == null){ + if (response == null) { getResourceRes = toscaOperationFacade.getToscaElement(componentId); - if(getResourceRes.isRight()){ - response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()))); + if (getResourceRes.isRight()) { + response = Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()))); } } - if(response == null){ + if (response == null) { response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters); } - } catch(Exception e){ + } 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 != null && response.isLeft()){ + } finally { + if (response != null && response.isLeft()) { toscaOperationFacade.commit(); } else { toscaOperationFacade.rollback(); @@ -766,22 +731,25 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return response; } - private Either>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map> filters) { - - Map> filteredProperties = new HashMap<>(); + 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); + 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); setFilteredProperties(filteredProperties, instance, 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 (component.getComponentInstancesInputs() != null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())) { + List currInputs = getFilteredComponentInstanceInputs( + component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); + if (CollectionUtils.isNotEmpty(currInputs)) { checkFilteredProperties(filteredProperties, instance, currInputs); } } @@ -790,34 +758,38 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return result; } - private void setFilteredProperties(Map> filteredProperties, ComponentInstance instance, List currProperties) { - if(CollectionUtils.isNotEmpty(currProperties)){ + private void setFilteredProperties(Map> filteredProperties, ComponentInstance instance, + List currProperties) { + if (CollectionUtils.isNotEmpty(currProperties)) { filteredProperties.put(instance.getUniqueId(), currProperties); } } - private void checkFilteredProperties(Map> filteredProperties, ComponentInstance instance, List currInputs) { - if(filteredProperties.get(instance.getUniqueId())!=null){ + private void checkFilteredProperties(Map> filteredProperties, ComponentInstance instance, + List currInputs) { + if (filteredProperties.get(instance.getUniqueId()) != null) { filteredProperties.get(instance.getUniqueId()).addAll(currInputs); } else { filteredProperties.put(instance.getUniqueId(), currInputs); } } - private List getFilteredComponentInstanceInputs(List inputs, String propertyNameFragment, boolean searchByFragment) { + 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) { + 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)){ + if (searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)) { isMatching = true; } - if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){ + if (!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)) { isMatching = true; } return isMatching; @@ -825,56 +797,50 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) { boolean isMatching = false; - if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){ + if (searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)) { isMatching = true; } - if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ + if (!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)) { isMatching = true; } - if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){ + if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())) { isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment); } return isMatching; } - private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) { + private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) { String propertyType; - List dataTypeProperties; + List dataTypeProperties; DataTypeDefinition currentProperty; - if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){ + if (searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())) { return true; } - if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ + if (!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)) { return true; } - propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType(); - - if(ToscaPropertyType.isScalarType(propertyType)){ + if (ToscaPropertyType.isScalarType(propertyType)) { return false; } - Either getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType); - if(getDataTypeByNameRes.isRight()){ + Either getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType); + if (getDataTypeByNameRes.isRight()) { return false; } currentProperty = getDataTypeByNameRes.left().value(); dataTypeProperties = currentProperty.getProperties(); - boolean dataPropertiesNotNull = CollectionUtils.isNotEmpty(dataTypeProperties); - BooleanSupplier dataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, - searchByFragment, dataTypeProperties); - BooleanSupplier parentPropertiesNotNull = () -> CollectionUtils - .isNotEmpty(currentProperty.getDerivedFrom().getProperties()); - BooleanSupplier parentDataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, - searchByFragment, currentProperty.getDerivedFrom().getProperties()); - - return ((dataPropertiesNotNull && dataMatchesComplexProperty.getAsBoolean()) - || (parentPropertiesNotNull.getAsBoolean() && parentDataMatchesComplexProperty.getAsBoolean())); + BooleanSupplier dataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, searchByFragment, dataTypeProperties); + BooleanSupplier parentPropertiesNotNull = () -> CollectionUtils.isNotEmpty(currentProperty.getDerivedFrom().getProperties()); + BooleanSupplier parentDataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, searchByFragment, + currentProperty.getDerivedFrom().getProperties()); + return ((dataPropertiesNotNull && dataMatchesComplexProperty.getAsBoolean()) || (parentPropertiesNotNull.getAsBoolean() + && parentDataMatchesComplexProperty.getAsBoolean())); } private boolean isMatchingComplexProperty(String propertyNameFragment, boolean searchByFragment, List dataTypeProperties) { - for(PropertyDefinition prop : dataTypeProperties){ - if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ + for (PropertyDefinition prop : dataTypeProperties) { + if (isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)) { return true; } } @@ -882,20 +848,22 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } private boolean isEmptyInnerType(PropertyDataDefinition property) { - return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null; + return property == null || property.getSchema() == null || property.getSchema().getProperty() == null + || property.getSchema().getProperty().getType() == null; } public Either shouldUpgradeToLatestGeneric(Component clonedComponent) { - - if(!clonedComponent.deriveFromGeneric()) + if (!clonedComponent.deriveFromGeneric()) { return Either.left(false); + } Boolean shouldUpgrade = false; String currentGenericType = clonedComponent.getDerivedFromGenericType(); String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion(); Resource genericTypeResource = fetchAndSetDerivedFromGenericType(clonedComponent); - if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){ + if (null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion + .equals(genericTypeResource.getVersion())) { shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource); - if(!shouldUpgrade) { + if (!shouldUpgrade) { reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion); } } @@ -907,42 +875,45 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); } - private Either, String> validateNoConflictingProperties(List currentList, List upgradedList) { + 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){ - + private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric) { List genericTypeProps = latestGeneric.getProperties(); - Either, String> validPropertiesMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); + Either, String> validPropertiesMerge = validateNoConflictingProperties(genericTypeProps, + ((Resource) componentToCheckOut).getProperties()); if (validPropertiesMerge.isRight()) { - log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validPropertiesMerge.right().value()); + log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", + validPropertiesMerge.right().value()); return false; } List genericTypeAttributes = latestGeneric.getAttributes(); - final Either, String> validAttributesMerge = validateNoConflictingProperties( - genericTypeAttributes, ((Resource) componentToCheckOut).getAttributes()); + final Either, String> validAttributesMerge = validateNoConflictingProperties(genericTypeAttributes, + ((Resource) componentToCheckOut).getAttributes()); if (validAttributesMerge.isRight()) { - log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validAttributesMerge.right().value()); + log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", + validAttributesMerge.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 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()) { + for (InputDefinition input : componentToCheckOut.getInputs()) { InputDefinition copy = new InputDefinition(input); copy.setOwnerId(null); currentList.add(copy); @@ -952,7 +923,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { 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()); @@ -962,17 +932,15 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return true; } - private List getFilteredInstances(Component component, List resourceTypes) { List filteredInstances = null; - if(CollectionUtils.isEmpty(resourceTypes)){ + 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()); } - else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ - filteredInstances = component.getComponentInstances() - .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList()); - } - if(filteredInstances == null){ + if (filteredInstances == null) { filteredInstances = new ArrayList<>(); } return filteredInstances; @@ -980,8 +948,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { private boolean isMatchingType(OriginTypeEnum originType, List resourceTypes) { boolean isMatchingType = false; - for(String resourceType : resourceTypes){ - if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){ + for (String resourceType : resourceTypes) { + if (originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())) { isMatchingType = true; break; } @@ -994,14 +962,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.right(ActionStatus.GENERAL_ERROR); } - protected Either updateCatalog(Component component, ChangeTypeEnum changeStatus){ - log.debug("update Catalog start with Component Type {} And Componet Name {} with change status {}", component.getComponentType().name(), component.getName(), changeStatus.name()); - ActionStatus status = catalogOperations.updateCatalog(changeStatus,component); - if(status != ActionStatus.OK){ - return Either.right( componentsUtils.getResponseFormat(status)); + protected Either updateCatalog(Component component, ChangeTypeEnum changeStatus) { + log.debug("update Catalog start with Component Type {} And Componet Name {} with change status {}", component.getComponentType().name(), + component.getName(), changeStatus.name()); + ActionStatus status = catalogOperations.updateCatalog(changeStatus, component); + if (status != ActionStatus.OK) { + return Either.right(componentsUtils.getResponseFormat(status)); } - - return Either.left(component); + return Either.left(component); } public CatalogOperation getCatalogOperations() { @@ -1016,5 +984,4 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { public List throwComponentException(ResponseFormat responseFormat) { throw new ByResponseFormatComponentException(responseFormat); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java index 1e0f6863f9..0a7758defb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java @@ -34,7 +34,8 @@ public class ComponentBusinessLogicProvider { private final ServiceBusinessLogic serviceBusinessLogic; private final ProductBusinessLogic productBusinessLogic; - public ComponentBusinessLogicProvider(ResourceBusinessLogic resourceBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, ProductBusinessLogic productBusinessLogic) { + public ComponentBusinessLogicProvider(ResourceBusinessLogic resourceBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, + ProductBusinessLogic productBusinessLogic) { this.resourceBusinessLogic = resourceBusinessLogic; this.serviceBusinessLogic = serviceBusinessLogic; this.productBusinessLogic = productBusinessLogic; @@ -43,16 +44,15 @@ public class ComponentBusinessLogicProvider { public ComponentBusinessLogic getInstance(ComponentTypeEnum componentTypeEnum) { switch (componentTypeEnum) { case SERVICE: - return serviceBusinessLogic; + return serviceBusinessLogic; case PRODUCT: - return productBusinessLogic; + return productBusinessLogic; case RESOURCE: case RESOURCE_INSTANCE: - return resourceBusinessLogic; + return resourceBusinessLogic; default: BeEcompErrorManager.getInstance().logBeSystemError("getInstance"); throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, componentTypeEnum.getValue()); } } - } 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 a18d8dc8e4..8515c5c468 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.be.components.attribute.GetOutputUtils.isGetOutputValueForOutput; @@ -142,7 +141,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph"; private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech"; private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */ - {"charts", "day0", "configtemplate"} /*cloud specific sub type*/}; + {"charts", "day0", "configtemplate"} /*cloud specific sub type*/}; private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}"; private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created."; private static final String INVALID_COMPONENT_TYPE = "invalid component type"; @@ -154,28 +153,28 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private static final String CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE = "Cannot attach resource instances to container resource of type {}"; private static final String SERVICE_PROXY = "serviceProxy"; private static final String ASSOCIATE_RI_TO_RI = "associateRIToRI"; - private ComponentInstanceOperation componentInstanceOperation; private ArtifactsBusinessLogic artifactBusinessLogic; private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator; private ForwardingPathOperation forwardingPathOperation; private NodeFilterOperation nodeFilterOperation; + @Autowired + private CompositionBusinessLogic compositionBusinessLogic; + @Autowired + private ContainerInstanceTypesData containerInstanceTypesData; @Autowired - public ComponentInstanceBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic, - ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL, - ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator, - ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public ComponentInstanceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic, + ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL, + ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator, + ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation, + ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.componentInstanceOperation = componentInstanceOperation; this.artifactBusinessLogic = artifactBusinessLogic; this.compInstMergeDataBL = compInstMergeDataBL; @@ -184,26 +183,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { this.nodeFilterOperation = nodeFilterOperation; } - @Autowired - private CompositionBusinessLogic compositionBusinessLogic; - - @Autowired - private ContainerInstanceTypesData containerInstanceTypesData; - public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true); } - public List getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, - String inputId) { + 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((s, ciPropList) -> { String ciName = ""; - Optional ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)) - .findAny(); + Optional ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny(); if (ciOp.isPresent()) { ciName = ciOp.get().getName(); } @@ -216,7 +207,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { }); } return resList; - } public List getComponentInstanceAttributesByOutputId(final org.openecomp.sdc.be.model.Component component, @@ -226,7 +216,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (org.apache.commons.collections4.MapUtils.isNotEmpty(componentInstancesAttributes)) { componentInstancesAttributes.forEach((s, componentInstanceAttributeList) -> { String ciName = ""; - final Optional ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny(); + final Optional ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)) + .findAny(); if (ciOp.isPresent()) { ciName = ciOp.get().getName(); } @@ -239,7 +230,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { }); } return resList; - } private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List inputsValues, @@ -256,11 +246,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - private void addCompInstanceAttribute(final String s, - final String ciName, - final ComponentInstanceAttribute attribute, - final List outputsValues, - final String outputId, + private void addCompInstanceAttribute(final String s, final String ciName, final ComponentInstanceAttribute attribute, + final List outputsValues, final String outputId, final List resList) { if (outputsValues != null && !outputsValues.isEmpty()) { for (final GetOutputValueDataDefinition outputData : outputsValues) { @@ -274,30 +261,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - public Optional getComponentInstancePropertyByPolicyId(Component component, - PolicyDefinition policy) { - + public Optional getComponentInstancePropertyByPolicyId(Component component, PolicyDefinition policy) { Optional propertyCandidate = getComponentInstancePropertyByPolicy(component, policy); - if (propertyCandidate.isPresent()) { ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get(); - Optional getPolicyCandidate = - getGetPolicyValueDataDefinition(policy, componentInstanceProperty); - - getPolicyCandidate.ifPresent(getPolicyValue -> - updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy)); + Optional getPolicyCandidate = getGetPolicyValueDataDefinition(policy, componentInstanceProperty); + getPolicyCandidate + .ifPresent(getPolicyValue -> updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy)); return Optional.of(componentInstanceProperty); } - return Optional.empty(); - } private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty, - GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) { + GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) { componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue()); List getPolicyValues = componentInstanceProperty.getGetPolicyValues(); - if(CollectionUtils.isNotEmpty(getPolicyValues)) { + if (CollectionUtils.isNotEmpty(getPolicyValues)) { getPolicyValues.remove(getPolicyValue); componentInstanceProperty.setGetPolicyValues(getPolicyValues); policyDefinition.setGetPolicyValues(getPolicyValues); @@ -305,45 +285,30 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private Optional getGetPolicyValueDataDefinition(PolicyDefinition policy, - ComponentInstanceProperty componentInstanceProperty) { + ComponentInstanceProperty componentInstanceProperty) { List getPolicyValues = policy.getGetPolicyValues(); - return getPolicyValues.stream() - .filter(getPolicyValue -> getPolicyValue - .getPropertyName() - .equals(componentInstanceProperty - .getName())) - .findAny(); + return getPolicyValues.stream().filter(getPolicyValue -> getPolicyValue.getPropertyName().equals(componentInstanceProperty.getName())) + .findAny(); } - private Optional getComponentInstancePropertyByPolicy(Component component, - PolicyDefinition policy) { - Map> componentInstancesProperties = - component.getComponentInstancesProperties(); - - if(MapUtils.isEmpty(componentInstancesProperties)) { + private Optional getComponentInstancePropertyByPolicy(Component component, PolicyDefinition policy) { + Map> componentInstancesProperties = component.getComponentInstancesProperties(); + if (MapUtils.isEmpty(componentInstancesProperties)) { return Optional.empty(); } - String instanceUniqueId = policy.getInstanceUniqueId(); - List componentInstanceProperties = - componentInstancesProperties.containsKey(instanceUniqueId) - ? componentInstancesProperties.get(instanceUniqueId) - : new ArrayList<>(); - - return componentInstanceProperties - .stream().filter(property -> property.getName().equals(policy.getName())).findAny(); + componentInstancesProperties.containsKey(instanceUniqueId) ? componentInstancesProperties.get(instanceUniqueId) : new ArrayList<>(); + return componentInstanceProperties.stream().filter(property -> property.getName().equals(policy.getName())).findAny(); } - public List getComponentInstanceInputsByInputId( - org.openecomp.sdc.be.model.Component component, String inputId) { + 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((s, ciPropList) -> { String ciName = ""; - Optional ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)) - .findAny(); + Optional ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny(); if (ciOp.isPresent()) { ciName = ciOp.get().getName(); } @@ -351,13 +316,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { for (ComponentInstanceInput prop : ciPropList) { List inputsValues = prop.getGetInputValues(); addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList); - } } }); } return resList; - } public List getComponentInstanceOutputsByOutputId(final org.openecomp.sdc.be.model.Component component, @@ -367,7 +330,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (ciInputsMap != null && !ciInputsMap.isEmpty()) { ciInputsMap.forEach((s, ciPropList) -> { String ciName = ""; - final Optional ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny(); + final Optional ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)) + .findAny(); if (ciOp.isPresent()) { ciName = ciOp.get().getName(); } @@ -375,13 +339,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { for (final ComponentInstanceOutput prop : ciPropList) { final List outputValues = prop.getGetOutputValues(); addCompInstanceOutput(s, ciName, prop, outputValues, outputId, resList); - } } }); } return resList; - } private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List inputsValues, @@ -398,11 +360,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - private void addCompInstanceOutput(final String s, - final String ciName, - final ComponentInstanceOutput prop, - final List outputsValues, - final String outputId, + private void addCompInstanceOutput(final String s, final String ciName, final ComponentInstanceOutput prop, + final List outputsValues, final String outputId, final List resList) { if (outputsValues != null && !outputsValues.isEmpty()) { for (final GetOutputValueDataDefinition outputData : outputsValues) { @@ -416,25 +375,20 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - public ComponentInstance createComponentInstance(final String containerComponentParam, - final String containerComponentId, final String userId, + public ComponentInstance createComponentInstance(final String containerComponentParam, final String containerComponentId, final String userId, final ComponentInstance resourceInstance, final boolean needLock) { final User user = validateUserExists(userId); validateUserNotEmpty(user, "Create component instance"); validateJsonBody(resourceInstance, ComponentInstance.class); final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - final org.openecomp.sdc.be.model.Component containerComponent = - validateComponentExists(containerComponentId, containerComponentType, null); - + final org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); if (ModelConverter.isAtomicComponent(containerComponent)) { if (log.isDebugEnabled()) { log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType()); } throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()); } - validateCanWorkOnComponent(containerComponent, userId); - Component origComponent = null; if (resourceInstance != null && containerComponentType != null) { final OriginTypeEnum originType = resourceInstance.getOriginType(); @@ -451,8 +405,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { overrideFields(origComponent, resourceInstance); compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance); } - return createComponent(needLock, containerComponent,origComponent, resourceInstance, user); - + return createComponent(needLock, containerComponent, origComponent, resourceInstance, user); } private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) { @@ -461,7 +414,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())); } Component origComponent = serviceProxyOrigin.left().value(); - StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent); if (isFillProxyRes(fillProxyRes)) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes)); @@ -471,55 +423,53 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) { - final Either getServiceResult = toscaOperationFacade.getToscaFullElement(resourceInstance.getComponentUid()); + final Either getServiceResult = toscaOperationFacade + .getToscaFullElement(resourceInstance.getComponentUid()); if (getServiceResult.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); } final Component service = getServiceResult.left().value(); - - final Either getServiceDerivedFromTypeResult = toscaOperationFacade.getLatestByToscaResourceName(service.getDerivedFromGenericType()); + final Either getServiceDerivedFromTypeResult = toscaOperationFacade + .getLatestByToscaResourceName(service.getDerivedFromGenericType()); if (getServiceDerivedFromTypeResult.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); } - Component origComponent = getServiceDerivedFromTypeResult.left().value(); - final StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent); if (isFillProxyRes(fillProxyRes)) { - throw new ByActionStatusComponentException( - componentsUtils.convertFromStorageResponse(fillProxyRes)); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes)); } return origComponent; } - private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) { - + private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, + ComponentInstance resourceInstance, User user) { boolean failed = false; try { - lockIfNeed(needLock, containerComponent); - log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { - if (needLock) + } finally { + if (needLock) { unlockComponent(failed, containerComponent); + } } } /** * Try using either to make a judgment + * * @param containerComponentParam * @param containerComponentId * @param userId * @param resourceInstance * @return */ - - public Either createRealComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { + public Either createRealComponentInstance(String containerComponentParam, String containerComponentId, + String userId, ComponentInstance resourceInstance) { log.debug("enter createRealComponentInstance"); return createRealComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true); } @@ -534,11 +484,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param resourceInstance * @return */ - public Either createRealComponentInstance(String containerComponentParam, - String containerComponentId, String userId, - ComponentInstance resourceInstance, + public Either createRealComponentInstance(String containerComponentParam, String containerComponentId, + String userId, ComponentInstance resourceInstance, boolean needLock) { - log.debug("enter createRealComponentInstance"); Component origComponent = null; User user; @@ -550,29 +498,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { validateJsonBody(resourceInstance, ComponentInstance.class); containerComponentType = validateComponentType(containerComponentParam); containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); - log.debug("enter createRealComponentInstance,validate user json success"); if (ModelConverter.isAtomicComponent(containerComponent)) { log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType()); throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()); } - validateCanWorkOnComponent(containerComponent, userId); log.debug("enter createRealComponentInstance,validateCanWorkOnComponent success"); - if (resourceInstance != null && containerComponentType != null) { log.debug("enter createRealComponentInstance,start create ComponentInstance"); OriginTypeEnum originType = resourceInstance.getOriginType(); validateInstanceName(resourceInstance); if (originType == OriginTypeEnum.ServiceProxy) { - log.debug("enter createRealComponentInstance,originType equals ServiceProxy"); Either serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY); if (isServiceProxyOrigin(serviceProxyOrigin)) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())); } origComponent = serviceProxyOrigin.left().value(); - StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent); if (isFillProxyRes(fillProxyRes)) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes)); @@ -588,52 +531,50 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug("enter createRealComponentInstance,final validate success"); } return createRealComponent(needLock, containerComponent, origComponent, resourceInstance, user); - } catch (ComponentException e) { log.debug("create Real Component Instance failed"); throw e; } } - private Either createRealComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) { - + private Either createRealComponent(boolean needLock, Component containerComponent, Component origComponent, + ComponentInstance resourceInstance, User user) { log.debug("enter createRealComponent"); boolean failed = false; try { - lockIfNeed(needLock, containerComponent); - log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); return createRealComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); } catch (ComponentException e) { failed = true; throw e; } finally { - if (needLock) + if (needLock) { unlockComponent(failed, containerComponent); + } } } - private Either createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { + private Either createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, + Component originComponent, + ComponentInstance componentInstance, User user) { log.debug("enter createRealComponentInstanceOnGraph"); - - Either, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); - + Either, StorageOperationStatus> result = toscaOperationFacade + .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); if (result.isRight()) { log.debug("enter createRealComponentInstanceOnGraph,result is right"); ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value()); log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName()); return Either.right(componentsUtils.getResponseFormat(status)); } - log.debug(ENTITY_ON_GRAPH_IS_CREATED); log.debug("enter createRealComponentInstanceOnGraph,Entity on graph is created."); Component updatedComponent = result.left().value().getLeft(); Map existingEnvVersions = new HashMap<>(); // TODO existingEnvVersions ?? addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); - - Optional updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst(); + 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()); throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()); @@ -648,18 +589,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private void validateInstanceName(ComponentInstance resourceInstance) { - String resourceInstanceName = resourceInstance.getName(); if (StringUtils.isEmpty(resourceInstanceName)) { log.debug("ComponentInstance name is empty"); throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName()); } - if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) { log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH); throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName()); } - if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) { log.debug("ComponentInstance name {} has invalid format", resourceInstanceName); throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName()); @@ -667,14 +605,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private void validateResourceInstanceState(Component containerComponent, Component origComponent) { - if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){ + if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE, - containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString()); + containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString()); } } - private void validateOriginAndResourceInstanceTypes(final Component containerComponent, - final Component origComponent, + private void validateOriginAndResourceInstanceTypes(final Component containerComponent, final Component origComponent, final OriginTypeEnum originType) { final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent); validateOriginType(originType, resourceType); @@ -686,14 +623,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { case SERVICE: if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType)) { throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE, - containerComponent.getComponentType().toString(), resourceType.name()); + containerComponent.getComponentType().toString(), resourceType.name()); } break; case RESOURCE: final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType(); if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) { throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE, - containerComponent.getComponentType().toString(), resourceType.name()); + containerComponent.getComponentType().toString(), resourceType.name()); } break; default: @@ -705,12 +642,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ResourceTypeEnum convertedOriginType; try { convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name()); + } catch (Exception e) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } - catch (Exception e){ + if (resourceType != convertedOriginType) { throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } - - if (resourceType != convertedOriginType) throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); } private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) { @@ -748,8 +685,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { filter.setIgnoreProperties(false); filter.setIgnoreAttributes(false); filter.setIgnoreInputs(false); - Either serviceRes = - toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter); + Either serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter); if (serviceRes.isRight()) { return serviceRes.right().value(); } @@ -759,12 +695,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { final Map> req = service.getRequirements(); resourceInstance.setRequirements(req); final Map serviceInterfaces = service.getInterfaces(); - if(MapUtils.isNotEmpty(serviceInterfaces)) { + if (MapUtils.isNotEmpty(serviceInterfaces)) { serviceInterfaces.forEach(resourceInstance::addInterface); } resourceInstance.setProperties(PropertiesUtils.getProperties(service)); resourceInstance.setAttributes(service.getAttributes()); - final List serviceInputs = service.getInputs(); resourceInstance.setInputs(serviceInputs); resourceInstance.setSourceModelInvariant(service.getInvariantUUID()); @@ -773,18 +708,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resourceInstance.setSourceModelUid(service.getUniqueId()); resourceInstance.setComponentUid(origComponent.getUniqueId()); resourceInstance.setComponentVersion(service.getVersion()); - - switch(resourceInstance.getOriginType()) { - case ServiceProxy: - return fillProxyInstanceData(resourceInstance, origComponent, service); - case ServiceSubstitution: - return fillServiceSubstitutableNodeTypeData(resourceInstance, service); - default: - return StorageOperationStatus.OK; + switch (resourceInstance.getOriginType()) { + case ServiceProxy: + return fillProxyInstanceData(resourceInstance, origComponent, service); + case ServiceSubstitution: + return fillServiceSubstitutableNodeTypeData(resourceInstance, service); + default: + return StorageOperationStatus.OK; } } - private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent, final Component service) { + private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent, + final Component service) { final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX; final String toscaResourceName = ((Resource) origComponent).getToscaResourceName(); final int lastIndexOf = toscaResourceName.lastIndexOf('.'); @@ -799,39 +734,32 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) { - resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName())); + resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName())); resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName())); resourceInstance.setIsProxy(false); resourceInstance.setDescription("A substitutable node type for service " + service.getName()); - return StorageOperationStatus.OK; } - public Either createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) { - + public Either createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, + String userId, CreateAndAssotiateInfo createAndAssotiateInfo) { Either resultOp = null; ComponentInstance resourceInstance = createAndAssotiateInfo.getNode(); RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate(); - User user = validateUserExists(userId); - final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); - 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())); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); } - validateCanWorkOnComponent(containerComponent, userId); - boolean failed = false; try { lockComponent(containerComponent, "createAndAssociateRIToRI"); log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); Component origComponent = getOriginComponentFromComponentInstance(resourceInstance); - log.debug(ENTITY_ON_GRAPH_IS_CREATED); ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) { @@ -839,25 +767,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } else { associationInfo.setToNode(resResourceInfo.getUniqueId()); } - - Either resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponent, containerComponentId, associationInfo); + Either resultReqCapDef = toscaOperationFacade + .associateResourceInstances(containerComponent, containerComponentId, associationInfo); if (resultReqCapDef.isLeft()) { log.debug(ENTITY_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)); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance( + componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null)); return resultOp; } - - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { unlockComponent(failed, containerComponent); } } @@ -874,27 +801,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId); if (eitherComponent.isRight()) { log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null); } return eitherComponent.left().value(); } - private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { - - Either, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); - + private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, + ComponentInstance componentInstance, User user) { + 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()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null)); + throw new ByResponseFormatComponentException(componentsUtils + .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", + null)); } - log.debug(ENTITY_ON_GRAPH_IS_CREATED); Component updatedComponent = result.left().value().getLeft(); Map existingEnvVersions = new HashMap<>(); // TODO existingEnvVersions ?? addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); - - Optional updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst(); + 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()); throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()); @@ -902,21 +831,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return updatedInstanceOptional.get(); } - public boolean isCloudSpecificArtifact(String artifact) { - if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) { - for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) { - if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) { - return false; - } - } - return true; - } else { - return false; - } - } + public boolean isCloudSpecificArtifact(String artifact) { + if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) { + for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) { + if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) { + return false; + } + } + return true; + } else { + return false; + } + } /** - * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts + * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's + * artifacts + * * @param containerComponent * @param componentInstance * @param originComponent @@ -924,8 +855,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param existingEnvVersions * @return */ - protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map existingEnvVersions) { - + protected ActionStatus 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 = new ArrayList<>(); ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance); @@ -936,30 +868,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { // generate heat_env if necessary Map componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts(); if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) { - Map finalDeploymentArtifacts = new HashMap<>(); Map> groupInstancesArtifacts = new HashMap<>(); - Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration() - .getHeatArtifactDeploymentTimeout().getDefaultMinutes(); + Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout() + .getDefaultMinutes(); List listOfCloudSpecificArts = new ArrayList<>(); 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.HELM.getType())|| type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) { + if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType()) || type + .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type + .equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) { artifact.setTimeout(defaultHeatTimeout); } else { continue; } if (artifact.checkEsIdExist()) { - ArtifactDefinition artifactDefinition = artifactBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(), - artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), - NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, - existingEnvVersions); + ArtifactDefinition artifactDefinition = artifactBusinessLogic + .createHeatEnvPlaceHolder(new ArrayList<>(), artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), + NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, existingEnvVersions); // 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()); } @@ -967,45 +898,47 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { listOfCloudSpecificArts.add(artifact); } if (CollectionUtils.isNotEmpty(filteredGroups)) { - filteredGroups.stream().filter(g -> - g.getArtifacts() - .stream() - .anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))) - .findFirst() - .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g)); + filteredGroups.stream() + .filter(g -> g.getArtifacts().stream().anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))).findFirst() + .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g)); } } } - groupInstancesArtifacts.forEach((k,v) -> v.addAll(listOfCloudSpecificArts)); + groupInstancesArtifacts.forEach((k, v) -> v.addAll(listOfCloudSpecificArts)); filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach(e -> { g.getArtifactsUuid().add(e.getArtifactUUID()); g.getArtifacts().add(e.getUniqueId()); })); - artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts); + 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); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); - + log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), + containerComponent.getUniqueId(), artStatus); + throw new ByResponseFormatComponentException( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); } - StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts); + StorageOperationStatus result = toscaOperationFacade + .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts); if (result != StorageOperationStatus.OK) { log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId()); throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); } componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); } - - artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts()); + 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); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); - + log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", + componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); + throw new ByResponseFormatComponentException( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); } componentInstance.setArtifacts(originComponent.getArtifacts()); return ActionStatus.OK; } - private void fillInstanceArtifactMap(Map> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, GroupDefinition groupInstance) { + private void fillInstanceArtifactMap(Map> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, + GroupDefinition groupInstance) { List artifactsUid; if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) { artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId()); @@ -1017,9 +950,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) { - Either, StorageOperationStatus> getResourceDeploymentArtifacts = - artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null); - + Either, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic + .getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null); Map deploymentArtifacts = new HashMap<>(); if (getResourceDeploymentArtifacts.isRight()) { StorageOperationStatus status = getResourceDeploymentArtifacts.right().value(); @@ -1030,7 +962,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } else { deploymentArtifacts = getResourceDeploymentArtifacts.left().value(); } - if (!deploymentArtifacts.isEmpty()) { Map tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts); for (Entry artifact : deploymentArtifacts.entrySet()) { @@ -1038,42 +969,37 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { tempDeploymentArtifacts.remove(artifact.getKey()); } } - resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts); } - return ActionStatus.OK; } - public Either updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) { + public Either updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, + String componentInstanceId, String userId, + ComponentInstance componentInstance) { return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, true); } - public Either updateComponentInstanceMetadata( - final String containerComponentParam, - final String containerComponentId, - final String componentInstanceId, - final String userId, - ComponentInstance componentInstance, - boolean needLock) { - + public Either updateComponentInstanceMetadata(final String containerComponentParam, + final String containerComponentId, + final String componentInstanceId, final String userId, + ComponentInstance componentInstance, boolean needLock) { validateUserExists(userId); - final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); - validateCanWorkOnComponent(containerComponent, userId); ComponentTypeEnum instanceType = getComponentType(containerComponentType); - Either validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid()); + Either validateParentStatus = toscaOperationFacade + .validateComponentExists(componentInstance.getComponentUid()); if (validateParentStatus.isRight()) { log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), + instanceType.getValue().toLowerCase()); } if (!validateParentStatus.left().value()) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), + instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId); } - if (needLock) { lockComponent(containerComponent, "updateComponentInstance"); } @@ -1081,11 +1007,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { boolean failed = false; try { origComponent = getOriginComponentFromComponentInstance(componentInstance); - componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance); - }catch (ComponentException e) { + componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, + componentInstance); + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { if (needLock) { unlockComponent(failed, containerComponent); } @@ -1094,12 +1021,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } // New Multiple Instance Update API - public List updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, String userId, List componentInstanceList, boolean needLock) { - + public List updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, + String userId, List componentInstanceList, boolean needLock) { boolean failed = false; try { validateUserExists(userId); - final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); ComponentParametersView componentFilter = new ComponentParametersView(); componentFilter.disableAll(); @@ -1109,65 +1035,67 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter); } validateCanWorkOnComponent(containerComponent, userId); - ComponentTypeEnum instanceType = getComponentType(containerComponentType); - for (ComponentInstance componentInstance : componentInstanceList) { boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId()); if (!validateParent) { throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), - instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), - containerComponentId); + instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId); } } - if (needLock) { lockComponent(containerComponent, "updateComponentInstance"); } - List updatedList = new ArrayList<>(); List instancesFromContainerComponent = containerComponent.getComponentInstances(); List listForUpdate = new ArrayList<>(); - if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) + if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) { containerComponent.setComponentInstances(componentInstanceList); - else { + } else { Iterator iterator = instancesFromContainerComponent.iterator(); while (iterator.hasNext()) { ComponentInstance origInst = iterator.next(); - Optional op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny(); + 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()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); + 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()); + throw new ByResponseFormatComponentException(componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); } listForUpdate.add(updatedCi); - } else + } else { listForUpdate.add(origInst); + } } containerComponent.setComponentInstances(listForUpdate); - - Either updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter); + 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()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); + CommonUtility + .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", + containerComponent.getName(), updateStatus.right().value()); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance( + componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); } - for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) { - Optional op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); + Optional op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())) + .findAny(); if (op.isPresent()) { updatedList.add(updatedInstance); } } } return updatedList; - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { if (needLock) { unlockComponent(failed, containerComponent); } @@ -1186,127 +1114,131 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, + private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, + org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, ComponentInstance componentInstance) { - Optional componentInstanceOptional; Either, StorageOperationStatus> updateRes = null; ComponentInstance oldComponentInstance = null; boolean isNameChanged = false; - - componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst(); + 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()); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", + componentInstance.getName(), containerComponent.getName()); throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()); } String oldComponentName; oldComponentInstance = componentInstanceOptional.get(); oldComponentName = oldComponentInstance.getName(); String newInstanceName = componentInstance.getName(); - if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) + if (oldComponentName != 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); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()); + 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); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), + componentInstance.getName()); } - if(!DirectivesUtil.isValid(componentInstance.getDirectives())) { - final String directivesStr = - componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] ")); + if (!DirectivesUtil.isValid(componentInstance.getDirectives())) { + final String directivesStr = componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] ")); CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, - "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", - oldComponentInstance.getName(), newInstanceName , - directivesStr); - throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), componentInstance.getName()); + "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", oldComponentInstance.getName(), + newInstanceName, directivesStr); + throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), + componentInstance.getName()); } - updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance)); + 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()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null)); + 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()); + throw new ByResponseFormatComponentException(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()); - - if (containerComponent instanceof Service){ - Either renameEither = - renameServiceFilter((Service) containerComponent, newInstanceName, - oldComponentInstance.getName()); + 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()); + } + if (containerComponent instanceof Service) { + Either renameEither = renameServiceFilter((Service) containerComponent, newInstanceName, + oldComponentInstance.getName()); if (renameEither.isRight()) { throw new ByResponseFormatComponentException(renameEither.right().value()); } - updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName); } } // endregion } String newInstanceId = updateRes.left().value().getRight(); - Optional updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst(); - + 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()); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), + containerComponent.getName()); + throw new ByResponseFormatComponentException( + componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); } - return componentInstanceOptional.get(); } private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) { Collection forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId()); Set updated = new ForwardingPathUtils() - .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, - componentInstance.getName()); + .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, componentInstance.getName()); updated.forEach(fp -> { Either resultEither = forwardingPathOperation - .updateForwardingPath(containerComponent.getUniqueId(), fp); - if (resultEither.isRight()){ - CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",containerComponent.getName(), resultEither.right().value()); + .updateForwardingPath(containerComponent.getUniqueId(), fp); + if (resultEither.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ", + containerComponent.getName(), resultEither.right().value()); } }); } - - public Either renameServiceFilter(final Service containerComponent, - final String newInstanceName, + public Either renameServiceFilter(final Service containerComponent, final String newInstanceName, final String oldInstanceName) { - - Map renamedNodesFilter = - ServiceFilterUtils.getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName); - for( Entry entry : renamedNodesFilter.entrySet()){ - Either - renameEither = nodeFilterOperation.updateNodeFilter( - containerComponent.getUniqueId(),entry.getKey(),entry.getValue()); - if (renameEither.isRight()){ - return Either.right(componentsUtils.getResponseFormatForResourceInstance( - componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), - containerComponent.getName(), null)); + Map renamedNodesFilter = ServiceFilterUtils + .getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName); + for (Entry entry : renamedNodesFilter.entrySet()) { + Either renameEither = nodeFilterOperation + .updateNodeFilter(containerComponent.getUniqueId(), entry.getKey(), entry.getValue()); + if (renameEither.isRight()) { + return Either.right(componentsUtils.getResponseFormatForResourceInstance( + componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), containerComponent.getName(), + null)); } - } return Either.left(null); } /** - * @param oldPrefix- - * The normalized old vf name - * @param newNormailzedPrefix- - * The normalized new vf name - * @param qualifiedGroupInstanceName- - * old Group Instance Name + * @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))) + if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName + .startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) { return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix); + } return qualifiedGroupInstanceName; } @@ -1315,42 +1247,37 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { oldComponentInstance.setModificationTime(System.currentTimeMillis()); oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString()); oldComponentInstance.setDirectives(newComponentInstance.getDirectives()); - if (oldComponentInstance.getGroupInstances() != null) - oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName()))); + if (oldComponentInstance.getGroupInstances() != null) { + oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), + ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName()))); + } return oldComponentInstance; } - public ComponentInstance deleteComponentInstance(final String containerComponentParam, - final String containerComponentId, - final String componentInstanceId, String userId) - throws BusinessLogicException { - + public ComponentInstance deleteComponentInstance(final String containerComponentParam, final String containerComponentId, + final String componentInstanceId, String userId) throws BusinessLogicException { validateUserExists(userId); final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); validateCanWorkOnComponent(containerComponent, userId); - boolean failed = false; final Optional componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId); if (!componentInstanceOptional.isPresent()) { - throw new BusinessLogicException(componentsUtils - .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND)); + throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND)); } ComponentInstance componentInstance = componentInstanceOptional.get(); - try { if (containerComponent instanceof Service || containerComponent instanceof Resource) { - final Either deleteServiceFilterEither = - nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId); + final Either deleteServiceFilterEither = nodeFilterOperation + .deleteNodeFilter(containerComponent, componentInstanceId); if (deleteServiceFilterEither.isRight()) { - final ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(), - containerComponentType); + final ActionStatus status = componentsUtils + .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType); janusGraphDao.rollback(); throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId)); } - final Either resultOp = deleteNodeFiltersFromComponentInstance( - containerComponent, componentInstance, containerComponentType, userId); + final Either resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, + componentInstance, containerComponentType, userId); if (resultOp.isRight()) { janusGraphDao.rollback(); throw new ByResponseFormatComponentException(resultOp.right().value()); @@ -1358,24 +1285,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } lockComponent(containerComponent, "deleteComponentInstance"); final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - - componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, - containerComponentType, deletedCompInstance); - final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId); + componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType, + deletedCompInstance); + final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator + .doOnDeleteInstanceOperations(containerComponent, componentInstanceId); if (ActionStatus.OK != onDeleteOperationsStatus) { throw new ByActionStatusComponentException(onDeleteOperationsStatus); } } catch (final ComponentException e) { failed = true; throw e; - } - finally { + } finally { unlockComponent(failed, containerComponent); } return componentInstance; } - /** + /** * Try to modify the delete and return two cases * * @param containerComponentParam @@ -1384,15 +1310,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { + public Either deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId, + String componentInstanceId, String userId) { log.debug("enter deleteAbstractComponentInstance"); validateUserExists(userId); - final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); validateCanWorkOnComponent(containerComponent, userId); - boolean failed = false; ComponentInstance deletedRelatedInst; try { @@ -1400,17 +1324,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { final Optional componentInstanceById = containerComponent.getComponentInstanceById(componentInstanceId); if (componentInstanceById.isPresent()) { ComponentInstance componentInstance = componentInstanceById.get(); - Either deleteServiceFilterEither = - nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId); + Either deleteServiceFilterEither = nodeFilterOperation + .deleteNodeFilter(containerComponent, componentInstanceId); if (deleteServiceFilterEither.isRight()) { log.debug("enter deleteAbstractComponentInstance:deleteServiceFilterEither is right, filed"); - ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(), - containerComponentType); + ActionStatus status = componentsUtils + .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType); janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName())); } - Either resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, - componentInstance, ComponentTypeEnum.SERVICE, userId); + Either resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, componentInstance, + ComponentTypeEnum.SERVICE, userId); if (resultOp.isRight()) { log.debug("enter deleteAbstractComponentInstance:resultOp is right, filed"); janusGraphDao.rollback(); @@ -1421,11 +1345,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug("enter deleteAbstractComponentInstance:"); lockComponent(containerComponent, "deleteComponentInstance"); ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - - deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, - containerComponentType, deletedCompInstance); - ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId); - log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}",onDeleteOperationsStatus); + deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType, + deletedCompInstance); + ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator + .doOnDeleteInstanceOperations(containerComponent, componentInstanceId); + log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}", onDeleteOperationsStatus); if (ActionStatus.OK != onDeleteOperationsStatus) { throw new ByActionStatusComponentException(onDeleteOperationsStatus); } @@ -1439,24 +1363,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.left(deletedRelatedInst); } - public Either deleteNodeFiltersFromComponentInstance( - final Component component, - final ComponentInstance componentInstance, - final ComponentTypeEnum containerComponentType, - final String userId) { - - final Set componentFiltersIDsToBeDeleted = - getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance); + public Either deleteNodeFiltersFromComponentInstance(final Component component, + final ComponentInstance componentInstance, + final ComponentTypeEnum containerComponentType, + final String userId) { + final Set componentFiltersIDsToBeDeleted = getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance); if (!componentFiltersIDsToBeDeleted.isEmpty()) { - final Set ids = component.getComponentInstances().stream() - .filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName())) + final Set ids = component.getComponentInstances().stream().filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName())) .map(ComponentInstance::getUniqueId).collect(Collectors.toSet()); - final Either, StorageOperationStatus> deleteComponentNodeFiltersEither = - nodeFilterOperation.deleteNodeFilters(component, ids); + final Either, StorageOperationStatus> deleteComponentNodeFiltersEither = nodeFilterOperation + .deleteNodeFilters(component, ids); if (deleteComponentNodeFiltersEither.isRight()) { final ActionStatus status = componentsUtils - .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), - containerComponentType); + .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), containerComponentType); return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName())); } for (final String id : ids) { @@ -1465,11 +1384,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get(); - componentInstanceToBeUpdated.setDirectives(Collections.emptyList()); - final Either componentInstanceResponseFormatEither = - updateComponentInstanceMetadata(containerComponentType.getValue(), component.getUniqueId(), - componentInstanceToBeUpdated.getUniqueId(), userId, componentInstanceToBeUpdated, false); + final Either componentInstanceResponseFormatEither = updateComponentInstanceMetadata( + containerComponentType.getValue(), component.getUniqueId(), componentInstanceToBeUpdated.getUniqueId(), userId, + componentInstanceToBeUpdated, false); if (componentInstanceResponseFormatEither.isRight()) { return componentInstanceResponseFormatEither; } @@ -1478,19 +1396,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.left(componentInstance); } - private Set getComponentFiltersRelatedToComponentInstance(String containerComponentId, - ComponentInstance componentInstance) { + private Set getComponentFiltersRelatedToComponentInstance(String containerComponentId, ComponentInstance componentInstance) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreComponentInstances(false); - Either componentFilterOrigin = - toscaOperationFacade.getToscaElement(containerComponentId, filter); + Either componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter); final Component component = componentFilterOrigin.left().value(); return ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance); } - ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, - ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { - if(containerComponentType == ComponentTypeEnum.SERVICE){ + ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType, + ComponentInstance componentInstance) { + if (containerComponentType == ComponentTypeEnum.SERVICE) { List pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName()); if (!pathIDsToBeDeleted.isEmpty()) { deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted); @@ -1499,48 +1415,43 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return componentInstance; } - private void deleteForwardingPaths(String serviceId, List pathIdsToDelete){ - + private void deleteForwardingPaths(String serviceId, List pathIdsToDelete) { Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if(storageStatus.isRight()) { + if (storageStatus.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value())); } - Either, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(), - Sets.newHashSet(pathIdsToDelete)); - - if(result.isRight()) { + Either, StorageOperationStatus> result = forwardingPathOperation + .deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete)); + if (result.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value())); } } - private List getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){ + private List getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId) { Collection allPaths = getForwardingPathDataDefinitions(containerComponentId); List pathIDsToBeDeleted = new ArrayList<>(); - - allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId )) - .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId())); - + allPaths.stream().filter(path -> isPathRelatedToComponent(path, componentInstanceId)) + .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId())); return pathIDsToBeDeleted; } private Collection getForwardingPathDataDefinitions(String containerComponentId) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreServicePath(false); - Either forwardingPathOrigin = toscaOperationFacade - .getToscaElement(containerComponentId, filter); + Either forwardingPathOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter); return forwardingPathOrigin.left().value().getForwardingPaths().values(); } - private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, - String componentInstanceId){ - return pathDataDefinition.getPathElements().getListToscaDataDefinition() - .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || - elementDataDefinition.getToNode() - .equalsIgnoreCase(componentInstanceId)); + private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId) { + return pathDataDefinition.getPathElements().getListToscaDataDefinition().stream().anyMatch( + elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || elementDataDefinition.getToNode() + .equalsIgnoreCase(componentInstanceId)); } - private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) { - Either, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId); + private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, + ComponentTypeEnum containerComponentType) { + 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); @@ -1548,26 +1459,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent); ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent); - if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) { - List inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); + 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, inputsToDelete); + StorageOperationStatus deleteInputsRes = toscaOperationFacade + .deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete); if (deleteInputsRes != StorageOperationStatus.OK) { log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId); - throw new ByActionStatusComponentException( - componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), + componentInstanceId); } } } if (CollectionUtils.isNotEmpty(containerComponent.getOutputs())) { - final List outputsToDelete = containerComponent.getOutputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); + final List outputsToDelete = containerComponent.getOutputs().stream() + .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(outputsToDelete)) { - final StorageOperationStatus deleteOutputsRes = toscaOperationFacade.deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete); + final StorageOperationStatus deleteOutputsRes = toscaOperationFacade + .deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete); if (deleteOutputsRes != StorageOperationStatus.OK) { log.debug("Failed to delete outputs of the component instance {} from container component. ", componentInstanceId); - throw new ByActionStatusComponentException( - componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType), componentInstanceId); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType), + componentInstanceId); } } } @@ -1588,8 +1502,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } 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())); + if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())) { + containerComponent.setComponentInstancesRelations( + containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)) + .collect(Collectors.toList())); } } @@ -1597,19 +1513,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId); } - public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { + public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, + ComponentTypeEnum componentTypeEnum) { return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, true); } public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean needLock) { - validateUserExists(userId); - RequirementCapabilityRelDef requirementCapabilityRelDef; - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null); - validateCanWorkOnComponent(containerComponent, userId); boolean failed = false; try { @@ -1617,22 +1530,21 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { lockComponent(containerComponent, ASSOCIATE_RI_TO_RI); } requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef); - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { - if (needLock) + } finally { + if (needLock) { unlockComponent(failed, containerComponent); + } } return requirementCapabilityRelDef; } public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) { - log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); - - Either result = toscaOperationFacade.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef); - + Either result = toscaOperationFacade + .associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef); if (result.isLeft()) { log.debug(ENTITY_ON_GRAPH_IS_CREATED); return result.left().value(); @@ -1642,7 +1554,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { String toNameOrId = ""; Either fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); Either toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); - toNameOrId = requirementDef.getFromNode(); fromNameOrId = requirementDef.getFromNode(); if (fromResult.isLeft()) { @@ -1651,12 +1562,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (toResult.isLeft()) { toNameOrId = toResult.left().value().getName(); } - - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance - (result.right().value(), true), fromNameOrId, toNameOrId, - requirementDef.getRelationships().get(0).getRelation().getRequirement()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), + fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()); } - } /** @@ -1666,12 +1574,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param componentTypeEnum * @return */ - public List batchDissociateRIFromRI( - String componentId, - String userId, - List requirementDefList, - ComponentTypeEnum componentTypeEnum) { - + public List batchDissociateRIFromRI(String componentId, String userId, + List requirementDefList, + ComponentTypeEnum componentTypeEnum) { validateUserExists(userId); org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null); validateCanWorkOnComponent(containerComponent, userId); @@ -1680,41 +1585,40 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { try { lockComponent(containerComponent, ASSOCIATE_RI_TO_RI); for (RequirementCapabilityRelDef requirementDef : requirementDefList) { - RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI( - componentId, userId, requirementDef, containerComponent.getComponentType()); + RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(componentId, userId, requirementDef, + containerComponent.getComponentType()); delOkResult.add(requirementCapabilityRelDef); } - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { unlockComponent(failed, containerComponent); } return delOkResult; } - public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { + public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, + ComponentTypeEnum componentTypeEnum) { validateUserExists(userId); - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null); - validateCanWorkOnComponent(containerComponent, userId); boolean failed = false; try { lockComponent(containerComponent, ASSOCIATE_RI_TO_RI); log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH); - Either result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef); + Either result = toscaOperationFacade + .dissociateResourceInstances(componentId, requirementDef); if (result.isLeft()) { log.debug(ENTITY_ON_GRAPH_IS_CREATED); return result.left().value(); } else { - log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); String fromNameOrId = ""; String toNameOrId = ""; - Either fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); + Either fromResult = getResourceInstanceById(containerComponent, + requirementDef.getFromNode()); Either toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); - toNameOrId = requirementDef.getFromNode(); fromNameOrId = requirementDef.getFromNode(); if (fromResult.isLeft()) { @@ -1723,57 +1627,57 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (toResult.isLeft()) { toNameOrId = toResult.left().value().getName(); } - throw new ByActionStatusComponentException( - componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), - fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()); + componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, + requirementDef.getRelationships().get(0).getRelation().getRequirement()); } - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { unlockComponent(failed, 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) { - + public Either getRelationById(String componentId, String relationId, String userId, + ComponentTypeEnum componentTypeEnum) { Either resultOp = null; try { org.openecomp.sdc.be.model.Component containerComponent = null; RequirementCapabilityRelDef foundRelation = null; - validateUserExists(userId); containerComponent = validateComponentExists(componentId, componentTypeEnum, null); List requirementCapabilityRelations = containerComponent.getComponentInstancesRelations(); foundRelation = findRelation(relationId, requirementCapabilityRelations); - if(foundRelation == null){ + 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){ + if (resultOp == null) { resultOp = setRelatedCapability(foundRelation, containerComponent); } - if(resultOp.isLeft()){ + 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)); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } return resultOp; } private RequirementCapabilityRelDef findRelation(String relationId, List requirementCapabilityRelations) { - for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){ + for (RequirementCapabilityRelDef relationship : requirementCapabilityRelations) { if (relationship.getRelationships().stream().anyMatch(r -> r.getRelation().getId().equals(relationId))) { return relationship; } @@ -1781,13 +1685,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return null; } - private Either setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) { + 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(); + 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", @@ -1807,12 +1712,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } if (result == null) { Either getfulfilledRequirementRes = toscaOperationFacade - .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, - this::isBelongingFullRequirement); + .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement); if (getfulfilledRequirementRes.isRight()) { ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), - instanceId, containerComponent.getUniqueId()); + .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); @@ -1827,24 +1731,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { - return req.getName().equals(relationshipInfo.getRequirement()) && - req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && - req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); + return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req + .getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); } private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) { - return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && - req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && - req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); + return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && req.getUniqueId() + .equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); } - private Either setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) { + 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(); + 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", @@ -1863,13 +1766,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } if (result == null) { - Either getfulfilledRequirementRes = - toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, - this::isBelongingFullCapability); + Either getfulfilledRequirementRes = toscaOperationFacade + .getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability); if (getfulfilledRequirementRes.isRight()) { ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), - instanceId, containerComponent.getUniqueId()); + .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); @@ -1877,73 +1779,61 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value()); } } - if(result == null){ + if (result == null) { result = Either.left(foundRelation); } return result; } private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { - return cap.getName().equals(relationshipInfo.getCapability()) && - cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && - cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); + return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap + .getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); } private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) { - return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && - cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && - cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); + return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && cap.getUniqueId() + .equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); } private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) { - return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? - currName.equals(nameFromRelationship): - previousName!= null && previousName.equals(nameFromRelationship); + return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? currName.equals(nameFromRelationship) + : previousName != null && previousName.equals(nameFromRelationship); } private Either updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { - Either eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); + 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); + 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; @@ -1959,10 +1849,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) { + public Either createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, + String resourceInstanceId, + ComponentInstanceProperty attribute, String userId) { Either result = null; Wrapper errorWrapper = new Wrapper<>(); - validateUserExists(userId); if (errorWrapper.isEmpty()) { validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper); @@ -1973,7 +1864,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (errorWrapper.isEmpty()) { validateComponentLock(componentId, componentTypeEnum, errorWrapper); } - try { if (errorWrapper.isEmpty()) { final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid()); @@ -1986,9 +1876,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { result = Either.right(errorWrapper.getInnerElement()); } return result; - } - - finally { + } finally { if (result == null || result.isRight()) { janusGraphDao.rollback(); } else { @@ -1999,10 +1887,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - public Either, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List properties, String userId) { - + public Either, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, + String componentId, String resourceInstanceId, + List properties, + String userId) { Either, ResponseFormat> resultOp = null; - /*-------------------------------Validations---------------------------------*/ validateUserExists(userId); @@ -2032,7 +1921,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); if (resourceInstanceStatus.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, - resourceInstanceId, "resource instance", "service", componentId)); + resourceInstanceId, "resource instance", "service", componentId)); } ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); @@ -2042,37 +1931,39 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug(FAILED_TO_LOCK_SERVICE, componentId); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } - List updatedProperties = new ArrayList<>(); + List updatedProperties = new ArrayList<>(); try { - for (ComponentInstanceProperty property: properties) { + for (ComponentInstanceProperty property : properties) { validateMandatoryFields(property); - ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance); + ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, + foundResourceInstance); String propertyParentUniqueId = property.getParentUniqueId(); Either updatedPropertyValue = updatePropertyObjectValue(property, false); if (updatedPropertyValue.isRight()) { log.error("Failed to update property object value of property: {}", - property); + property); throw new ByResponseFormatComponentException(updatedPropertyValue.right().value()); } Optional - capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities()); + capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities()); if (capPropDefinition.isPresent()) { updatedPropertyValue - .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue, - containerComponent, foundResourceInstance, capPropDefinition.get().getType(), - capPropDefinition.get().getName()), Either::right); + .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue, + containerComponent, foundResourceInstance, capPropDefinition.get().getType(), + capPropDefinition.get().getName()), Either::right); } else { updatedPropertyValue.bimap( - updatedValue -> { - componentInstanceProperty.setValue(updatedValue); - return updatePropertyOnContainerComponent(property, updatedValue, - containerComponent, foundResourceInstance); - }, Either::right); + updatedValue -> { + componentInstanceProperty.setValue(updatedValue); + return updatePropertyOnContainerComponent(property, updatedValue, + containerComponent, foundResourceInstance); + }, Either::right); updatedProperties.add(componentInstanceProperty); } } - Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + Either updateContainerRes = toscaOperationFacade + .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); if (updateContainerRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); @@ -2094,13 +1985,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private void validateMandatoryFields(PropertyDataDefinition property) { if (StringUtils.isEmpty(property.getName())) { - throw new ByActionStatusComponentException (ActionStatus.MISSING_PROPERTY_NAME); + throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME); } } - private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, ComponentInstance foundResourceInstance) { - List instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId()); - Optional instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())).findAny(); + private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, + ComponentInstance foundResourceInstance) { + List instanceProperties = containerComponent.getComponentInstancesProperties() + .get(foundResourceInstance.getUniqueId()); + Optional instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())) + .findAny(); if (!instanceProperty.isPresent()) { throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName()); } @@ -2108,11 +2002,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, - String newValue, Component containerComponent, ComponentInstance foundResourceInstance, + String newValue, Component containerComponent, + ComponentInstance foundResourceInstance, String capabilityType, String capabilityName) { String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent, - foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId); + foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId); if (actionStatus != null) { return actionStatus; } @@ -2126,13 +2021,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { String capabilityType, String capabilityName) { String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); Either getComponentRes = - toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid()); - if(getComponentRes.isRight()) { + toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid()); + if (getComponentRes.isRight()) { return componentsUtils.getResponseFormat(getComponentRes.right().value()); } ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent, - foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId); + foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId); if (actionStatus != null) { return actionStatus; } @@ -2155,20 +2050,22 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { List capProperties = cap.get().getProperties(); if (capProperties != null) { Optional instanceProperty = - capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); StorageOperationStatus status; if (instanceProperty.isPresent()) { - String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get()); + String capKey = ModelConverter + .buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, + componentInstanceUniqueId, cap.get()); 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()); + componentInstanceUniqueId, capKey, instanceProperty.get()); if (status != StorageOperationStatus.OK) { ActionStatus actionStatus = - componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); } @@ -2179,7 +2076,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return null; } - private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) { + private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, + Component containerComponent, ComponentInstance foundResourceInstance) { StorageOperationStatus status; instanceProperty.setValue(newValue); status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty); @@ -2191,19 +2089,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return componentsUtils.getResponseFormat(ActionStatus.OK); } - private Either validatePropertyObjectValue(T property, String newValue, boolean isInput) { + private Either validatePropertyObjectValue(T property, String newValue, boolean isInput) { Either, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); if (allDataTypesEither.isRight()) { JanusGraphOperationStatus 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.convertJanusGraphStatusToStorageStatus(status)))); + BeEcompErrorManager.getInstance() + .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, + ErrorSeverity.ERROR); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } Map allDataTypes = allDataTypesEither.left().value(); String propertyType = property.getType(); String innerType = getInnerType(property); // Specific Update Logic - Either isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes); + Either isValid = propertyOperation + .validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes); if (isValid.isRight()) { Boolean res = isValid.right().value(); if (!res) { @@ -2216,14 +2118,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { newValue = object.toString(); } } - if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); + if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils + .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); + } return Either.left(newValue); } - private boolean validateAndUpdateRules(T property, boolean isInput, Map allDataTypes, String innerType, String propertyType) { + private boolean validateAndUpdateRules(T property, boolean isInput, Map allDataTypes, + String innerType, String propertyType) { if (!isInput) { - ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); + ImmutablePair pair = propertyOperation + .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); if (pair.getRight() != null && !pair.getRight()) { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); return true; @@ -2232,12 +2138,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return false; } - private Either updatePropertyObjectValue(T property, boolean isInput) { + private Either updatePropertyObjectValue(T property, boolean isInput) { Either, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll(); if (allDataTypesEither.isRight()) { JanusGraphOperationStatus 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.convertJanusGraphStatusToStorageStatus(status)))); + BeEcompErrorManager.getInstance() + .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, + ErrorSeverity.ERROR); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } Map allDataTypes = allDataTypesEither.left().value(); String innerType = null; @@ -2249,23 +2158,27 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { 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))); + 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))); + 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); + Either isValid = propertyOperation + .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); String newValue = property.getValue(); if (isValid.isRight()) { Boolean res = isValid.right().value(); if (!res) { log.debug("validate and update property value has failed with value: {}", property.getValue()); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } } else { Object object = isValid.left().value(); @@ -2274,16 +2187,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } if (!isInput) { - ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); + 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.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)))); } } return Either.left(newValue); } - private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) { + private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, + ComponentInstance foundResourceInstance) { StorageOperationStatus status; input.setValue(newValue); status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input); @@ -2295,7 +2211,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return componentsUtils.getResponseFormat(ActionStatus.OK); } - public Either, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List inputs, String userId) { + public Either, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, + String componentId, String resourceInstanceId, + List inputs, + String userId) { Either, ResponseFormat> resultOp = null; @@ -2327,7 +2246,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); if (resourceInstanceStatus.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, - resourceInstanceId, "resource instance", "service", componentId)); + resourceInstanceId, "resource instance", "service", componentId)); } ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); @@ -2338,19 +2257,21 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug(FAILED_TO_LOCK_SERVICE, componentId); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } - List updatedInputs = new ArrayList<>(); + List updatedInputs = new ArrayList<>(); try { - for (ComponentInstanceInput input: inputs) { + for (ComponentInstanceInput input : inputs) { validateMandatoryFields(input); ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance); Either validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true); - if (validatedInputValue.isRight()){ + if (validatedInputValue.isRight()) { throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName()); } - updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, foundResourceInstance); + updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, + foundResourceInstance); updatedInputs.add(componentInstanceInput); } - Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + Either updateContainerRes = toscaOperationFacade + .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); if (updateContainerRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); @@ -2371,7 +2292,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } - private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, ComponentInstance foundResourceInstance) { + private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, + ComponentInstance foundResourceInstance) { List instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId()); Optional instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny(); if (!instanceInput.isPresent()) { @@ -2380,7 +2302,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return instanceInput.get(); } - public Either createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, String userId) { + public Either createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, + String componentId, String resourceInstanceId, + String groupInstanceId, + ComponentInstanceProperty property, + String userId) { Either resultOp = null; @@ -2409,7 +2335,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (propertyValueUid == null) { - Either counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId); + Either counterRes = groupInstanceOperation + .increaseAndGetGroupInstancePropertyCounter(groupInstanceId); if (counterRes.isRight()) { log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property); @@ -2418,7 +2345,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); } Integer index = counterRes.left().value(); - Either result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true); + Either result = groupInstanceOperation + .addPropertyValueToGroupInstance(property, resourceInstanceId, index, true); if (result.isLeft()) { log.trace("Property value was added to resource instance {}", resourceInstanceId); @@ -2435,7 +2363,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } else { - Either result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true); + Either result = groupInstanceOperation + .updatePropertyValueInGroupInstance(property, resourceInstanceId, true); if (result.isLeft()) { log.debug("Property value {} was updated on graph.", property.getValueUniqueUid()); @@ -2474,7 +2403,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } - public Either deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) { + public Either deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, + String resourceInstanceId, String propertyValueId, String userId) { validateUserExists(userId); @@ -2499,7 +2429,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } try { - Either result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true); + Either result = propertyOperation + .removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true); if (result.isLeft()) { log.debug("Property value {} was removed from graph.", propertyValueId); @@ -2536,7 +2467,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Component component; 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()); + 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); throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING); } @@ -2544,14 +2476,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { LifecycleStateEnum resourceCurrState = component.getLifecycleState(); if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE; - throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString()); + throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString()); } - if (component.isArchived() == true){ + if (component.isArchived() == true) { ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED; throw new ByActionStatusComponentException(actionStatus, component.getName()); } final Map componentInterfaces = component.getInterfaces(); - if(MapUtils.isNotEmpty(componentInterfaces)) { + if (MapUtils.isNotEmpty(componentInterfaces)) { componentInterfaces.forEach(componentInstance::addInterface); } return component; @@ -2570,10 +2502,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { //Fetch current component instance Either eitherResourceInstance = - getResourceInstanceById(containerComponent, componentInstanceId); + getResourceInstanceById(containerComponent, componentInstanceId); if (eitherResourceInstance.isRight()) { resultOp = Either.right(componentsUtils.getResponseFormat( - ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); + ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); return resultOp; } ComponentInstance currentResourceInstance = eitherResourceInstance.left().value(); @@ -2584,7 +2516,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (componentExistsRes.isRight()) { log.debug("Failed to find resource {}", resourceId); resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse - (componentExistsRes.right().value()), resourceId)); + (componentExistsRes.right().value()), resourceId)); return resultOp; } else if (!componentExistsRes.left().value()) { log.debug("The resource {} not found ", resourceId); @@ -2593,24 +2525,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } //Fetch component using new component instance uid - Component updatedContainerComponent=getOriginComponentFromComponentInstance(newComponentInstance); + Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance); Set toDeleteForwardingPaths = getForwardingPaths(containerComponent, - currentResourceInstance, updatedContainerComponent); - resultOp=Either.left(toDeleteForwardingPaths); + currentResourceInstance, updatedContainerComponent); + resultOp = Either.left(toDeleteForwardingPaths); return resultOp; } private Set getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance, Component updatedContainerComponent) { - DataForMergeHolder dataForMergeHolder=new DataForMergeHolder(); + DataForMergeHolder dataForMergeHolder = new DataForMergeHolder(); dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName()); Service service = (Service) containerComponent; ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils(); return forwardingPathUtils. - getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent); + getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent); } private ComponentParametersView getComponentParametersViewForForwardingPath() { @@ -2620,32 +2552,35 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return componentParametersView; } - public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) { + public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, + String userId, ComponentInstance newComponentInstance) { User user = validateUserExists(userId); final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.setIgnoreCapabiltyProperties(false); - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView); + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, + componentParametersView); validateCanWorkOnComponent(containerComponent, userId); Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId); if (resourceInstanceStatus.isRight()) { - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, + containerComponentId); } ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value(); - return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType ); + return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType); } public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, - ComponentInstance currentResourceInstance, - ComponentInstance newComponentInstance, - User user, - final ComponentTypeEnum containerComponentType) { + ComponentInstance currentResourceInstance, + ComponentInstance newComponentInstance, + User user, + final ComponentTypeEnum containerComponentType) { boolean failed = false; Either resourceInstanceStatus; @@ -2699,17 +2634,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { throw new ByActionStatusComponentException( componentsUtils.convertFromStorageResponse(fillProxyRes)); } - } else if (originType == OriginTypeEnum.ServiceSubstitution){ - final Either getServiceResult = toscaOperationFacade.getToscaFullElement(newComponentInstance.getComponentUid()); - if (getServiceResult.isRight()) { - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); - } - final Component service = getServiceResult.left().value(); - - final Either getServiceDerivedFromTypeResult = toscaOperationFacade.getLatestByToscaResourceName(service.getDerivedFromGenericType()); - if (getServiceDerivedFromTypeResult.isRight()) { - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); - } + } else if (originType == OriginTypeEnum.ServiceSubstitution) { + final Either getServiceResult = toscaOperationFacade + .getToscaFullElement(newComponentInstance.getComponentUid()); + if (getServiceResult.isRight()) { + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); + } + final Component service = getServiceResult.left().value(); + + final Either getServiceDerivedFromTypeResult = toscaOperationFacade + .getLatestByToscaResourceName(service.getDerivedFromGenericType()); + if (getServiceDerivedFromTypeResult.isRight()) { + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); + } origComponent = getServiceDerivedFromTypeResult.left().value(); @@ -2775,7 +2712,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } // US831698 - public List getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) { + public List getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, + String componentInstanceUniqueId, String userId) { Component containerComponent = null; boolean failed = false; @@ -2785,13 +2723,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { Either validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId); if (validateContainerComponentExists.isRight()) { - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())); } containerComponent = validateContainerComponentExists.left().value(); - Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, + componentInstanceUniqueId); if (resourceInstanceStatus.isRight()) { - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, + containerComponentId); } List instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId); @@ -2868,13 +2809,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { + public Either updateComponentInstanceModificationTimeAndCustomizationUuid( + ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { Either result; - Either updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime, + 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()))); + 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()); } @@ -2896,12 +2841,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.left(new ComponentInstance()); } - private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { + 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 = Either.right(StorageOperationStatus.NOT_FOUND); List instances = containerComponent.getComponentInstances(); Optional foundInstance = Optional.empty(); @@ -2920,38 +2865,33 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } 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())) + if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) { resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) + } + if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) { resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) + } + if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) { resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) + } + if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) { resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName()); - + } if (resourceInstanceForUpdate.getOriginType() == null) { resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType()); } - if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) + if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) { resourceInstanceForUpdate.setIsProxy(true); + } if (resourceInstanceForUpdate.getSourceModelInvariant() == null) { resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant()); } @@ -2969,8 +2909,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } return resourceInstanceForUpdate; } + /** * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId + * * @param containerComponentType * @param containerComponentId * @param componentInstanceUniqueId @@ -2980,10 +2922,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param ownerId * @return */ - public List getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) { - + public List getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, + String componentInstanceUniqueId, String capabilityType, + String capabilityName, String ownerId, String userId) { Component containerComponent = null; - List resultOp = null; try { validateUserExists(userId); @@ -3002,12 +2944,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - private List findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map> instanceCapabilities) { + private List findCapabilityOfInstance(String componentId, String instanceId, String capabilityType, + String capabilityName, String ownerId, + Map> instanceCapabilities) { 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(); + Optional capabilityOpt = capabilitiesPerType.stream() + .filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst(); if (capabilityOpt.isPresent()) { foundCapability = capabilityOpt.get(); return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties(); @@ -3017,43 +2962,42 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId); } - private List fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) { + private List fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, + String capabilityName, String ownerId) { try { return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId) - .left() - .on(this::componentInstancePropertyListException); - } catch(Exception e){ - log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e); + .left().on(this::componentInstancePropertyListException); + } catch (Exception e) { + log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, + capabilityName, e); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } } public Either updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, - RequirementDefinition requirementDef, String userId) { - + RequirementDefinition requirementDef, String userId) { Either resultOp = null; - validateUserExists(userId); if (componentTypeEnum == null) { BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", 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); + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, + componentInstanceUniqueId); if (resourceInstanceStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); @@ -3061,15 +3005,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug("Failed to lock component {}", containerComponentId); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } - try { - StorageOperationStatus updateRequirementStatus = toscaOperationFacade.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef); + StorageOperationStatus updateRequirementStatus = toscaOperationFacade + .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef); if (updateRequirementStatus != StorageOperationStatus.OK) { - log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId, containerComponentId); + log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId, + containerComponentId); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus))); } - Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - + Either updateContainerRes = toscaOperationFacade + .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); if (updateContainerRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); @@ -3077,7 +3022,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } resultOp = Either.left(requirementDef); return resultOp; - } finally { if (resultOp == null || resultOp.isRight()) { janusGraphDao.rollback(); @@ -3089,30 +3033,33 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - public Either, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, - List properties, String userId) { + public Either, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, + String containerComponentId, + String componentInstanceUniqueId, + String capabilityType, String capabilityName, + List properties, + String userId) { Either, ResponseFormat> resultOp = null; - validateUserExists(userId); 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); + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, + componentInstanceUniqueId); if (resourceInstanceStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); } ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); // lock resource @@ -3121,16 +3068,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug("Failed to lock component {}", containerComponentId); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } - try { for (ComponentInstanceProperty property : properties) { Either newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false); - newPropertyValueEither.bimap(updatedValue -> - updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName), - Either::right); + newPropertyValueEither.bimap( + updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, + capabilityType, capabilityName), Either::right); } - Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - + Either updateContainerRes = toscaOperationFacade + .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); if (updateContainerRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); @@ -3138,7 +3084,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } resultOp = Either.left(properties); return resultOp; - } finally { if (resultOp == null || resultOp.isRight()) { janusGraphDao.rollback(); @@ -3151,62 +3096,46 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } public Either, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance, - String containerComponentId, - String componentInstanceId, + String containerComponentId, String componentInstanceId, String userId) { - Map resultMap = new HashMap<>(); Either getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId); if (getOrigComponent.isRight()) { log.error("Failed to get the original component information"); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS)); } - Component origComponent = getOrigComponent.left().value(); - try { lockComponent(origComponent, "copyComponentInstance"); - } catch (ComponentException e) { log.error("destComponentInstance's data is {}", origComponent.toString()); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", origComponent.toString())); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", + origComponent.toString())); } - boolean failed = false; ComponentInstance actionResponse = null; try { - - actionResponse = createComponentInstance( - "services", containerComponentId, userId, inputComponentInstance, false); - + actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false); } catch (ComponentException e) { failed = true; // on failure of the create instance unlock the resource and rollback the transaction. return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS)); } finally { - // on failure of the create instance unlock the resource and rollback the transaction. if (null == actionResponse) { log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS); - unlockComponent(failed, origComponent); } } - Either resultOp = null; - try { ComponentInstance destComponentInstance = actionResponse; log.debug("destComponentInstance's data is {}", destComponentInstance); - resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId); - resultMap.put("componentInstance", destComponentInstance); } finally { // unlock resource - if (resultOp == null || resultOp.isRight()) { unlockComponent(true, origComponent); janusGraphDao.rollback(); @@ -3218,66 +3147,58 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } if (resultOp == null || resultOp.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas")); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas")); } else { return Either.left(resultMap); } - } - private Either deepCopyComponentInstance( - Component sourceComponent, String containerComponentId, String sourceComponentInstanceId, - ComponentInstance destComponentInstance, String userId) { - + private Either deepCopyComponentInstance(Component sourceComponent, String containerComponentId, + String sourceComponentInstanceId, ComponentInstance destComponentInstance, + String userId) { Either getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId); if (getDestComponent.isRight()) { log.error("Failed to get the dest component information"); return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS)); } - Component destComponent = getDestComponent.left().value(); - - Either copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs( - sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance); + Either copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent, + destComponent, sourceComponentInstanceId, destComponentInstance); if (copyComponentInstanceWithPropertiesAndInputs.isRight()) { log.error("Failed to copy component instance with properties and inputs as part of deep copy"); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy")); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, + "Failed to copy the component instance with properties and inputs as part of deep copy")); } - - Either copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes( - sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId); + Either copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent, + sourceComponentInstanceId, destComponentInstance, userId); if (copyComponentInstanceWithAttributes.isRight()) { log.error("Failed to copy component instance with attributes as part of deep copy"); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy")); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy")); } return Either.left(COPY_COMPONENT_INSTANCE_OK); } - private Either copyComponentInstanceWithPropertiesAndInputs( - Component sourceComponent, Component destComponent, String sourceComponentInstanceId, - ComponentInstance destComponentInstance) { + private Either copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent, + String sourceComponentInstanceId, + ComponentInstance destComponentInstance) { log.debug("start to copy ComponentInstance with properties and inputs"); - List sourcePropList = null; if (sourceComponent.getComponentInstancesProperties() != null && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) { sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId); log.debug("sourcePropList"); } - List destPropList = null; String destComponentInstanceId = destComponentInstance.getUniqueId(); log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId()); if (destComponent.getComponentInstancesProperties() != null - && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) { + && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) { destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId); log.debug("destPropList {}"); } - List componentInstancePropInputList = new ArrayList<>(); - if (null != destPropList && null != sourcePropList) { log.debug("start to set property and attribute"); for (ComponentInstanceProperty destProp : destPropList) { @@ -3288,32 +3209,28 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } log.debug("now set property"); final List getInputValues = sourceProp.getGetInputValues(); - if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) - && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) { + if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue() + .equals(sourceProp.getValue()))) { log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue()); - destProp.setValue(sourceProp.getValue()); - Either updatePropertyValueEither = updateComponentInstanceProperty( - destComponent.getUniqueId(), destComponentInstanceId, destProp); + Either updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(), + destComponentInstanceId, destProp); if (updatePropertyValueEither.isRight()) { log.error("Failed to copy the property {}", destPropertyName); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy")); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, + "Failed to paste component instance to the canvas, property copy")); } break; } - log.debug("Now start to update inputs"); - if (getInputValues != null) { if (getInputValues.isEmpty()) { log.debug("property is return from input, set by man"); break; } log.debug("Now starting to copy the {} property", destPropertyName); - - Either getSourceInputDefaultValue = getInputListDefaultValue( - sourceComponent, getInputValues.get(0).getInputId()); + Either getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent, + getInputValues.get(0).getInputId()); if (getSourceInputDefaultValue.isRight()) { return Either.right(getSourceInputDefaultValue.right().value()); } @@ -3325,121 +3242,93 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.left(COPY_COMPONENT_INSTANCE_OK); } - private Either copyComponentInstanceWithAttributes(Component sourceComponent, - Component destComponent, + private Either copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent, String sourceComponentInstanceId, - ComponentInstance destComponentInstance, - String userId) { + ComponentInstance destComponentInstance, String userId) { String destComponentInstanceId = destComponentInstance.getUniqueId(); - log.info("start to copy component instance with attributes"); - List sourceAttributeList = null; if (sourceComponent.getComponentInstancesAttributes() != null - && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) { + && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) { sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId); log.info("sourceAttributes {}"); } - List destAttributeList = null; if (destComponent.getComponentInstancesAttributes() != null - && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) { + && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) { destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId); log.info("destAttributeList {}"); } if (null != sourceAttributeList && null != destAttributeList) { log.info("set attribute"); - for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) { String sourceAttributeName = sourceAttribute.getName(); for (ComponentInstanceAttribute destAttribute : destAttributeList) { if (sourceAttributeName.equals(destAttribute.getName())) { log.debug("Start to copy the attribute exists {}", sourceAttributeName); - sourceAttribute.setUniqueId( - UniqueIdBuilder.buildResourceInstanceUniuqeId( - "attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName)); - - Either updateAttributeValueEither = - createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE, - destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, - userId); + UniqueIdBuilder.buildResourceInstanceUniuqeId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName)); + Either updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste( + ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId); if (updateAttributeValueEither.isRight()) { log.error("Failed to copy the attribute"); - return Either.right(componentsUtils - .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, - "Failed to paste component instance to the canvas, attribute copy")); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, + "Failed to paste component instance to the canvas, attribute copy")); } break; } } } } - return Either.left(COPY_COMPONENT_INSTANCE_OK); } private Either createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum, - String componentId, - String resourceInstanceId, - ComponentInstanceAttribute attribute, - String userId) { - + String componentId, String resourceInstanceId, + ComponentInstanceAttribute attribute, + String userId) { Either resultOp = null; - validateUserExists(userId); - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError( - "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateAttributeValue", 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.info("Failed to retrieve component id {}", componentId); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return resultOp; } - Component containerComponent = getResourceResult.left().value(); - Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat( - ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); + resultOp = Either + .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); return resultOp; } - ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - - String propertyType = attribute.getType(); ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType); - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { SchemaDefinition def = attribute.getSchema(); if (def == null) { log.info("Schema doesn't exists for attribute of type {}", type); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + return Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); } PropertyDataDefinition propDef = def.getProperty(); if (propDef == null) { log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + return Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); } } - List instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId); - Optional instanceAttribute = instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny(); + Optional instanceAttribute = instanceAttributes.stream() + .filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny(); StorageOperationStatus status; - if (instanceAttribute.isPresent()) { log.info("updateComponentInstanceAttribute"); status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute); @@ -3455,54 +3344,41 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { List path = new ArrayList<>(); path.add(foundResourceInstance.getUniqueId()); attribute.setPath(path); - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); - Either updateContainerRes = toscaOperationFacade. - updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - + Either updateContainerRes = toscaOperationFacade + .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils. - convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); - resultOp = Either.right(componentsUtils. - getResponseFormatForResourceInstanceProperty(actionStatus, "")); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); return resultOp; } resultOp = Either.left(attribute); return resultOp; } - private Either updateComponentInstanceProperty(String containerComponentId, - String componentInstanceId, + private Either updateComponentInstanceProperty(String containerComponentId, String componentInstanceId, ComponentInstanceProperty property) { Either resultOp; Either getComponent = toscaOperationFacade.getToscaElement(containerComponentId); - if (getComponent.isRight()) { log.error("Failed to get the component information"); - return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty( - ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information")); + return Either.right(componentsUtils + .getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information")); } - Component containerComponent = getComponent.left().value(); - - StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty( - containerComponent, componentInstanceId, property); + StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property); if (status != StorageOperationStatus.OK) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); return resultOp; } - - Either updateContainerRes = toscaOperationFacade. - updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - + Either updateContainerRes = toscaOperationFacade + .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils. - convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); return resultOp; } - return Either.left("Update OK"); } @@ -3518,34 +3394,31 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } log.error("The input's default value with id {} is not found", inputId); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas")); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas")); } /** * Method to delete selected nodes and edges on composition page + * * @param containerComponentType * @param componentId * @param componentInstanceIdList * @param userId * @return */ - public Map> batchDeleteComponentInstance(String containerComponentType, - String componentId, - List componentInstanceIdList, - String userId) { - + public Map> batchDeleteComponentInstance(String containerComponentType, String componentId, + List componentInstanceIdList, String userId) { List deleteErrorIds = new ArrayList<>(); Map> deleteErrorMap = new HashMap<>(); validateUserExists(userId); - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, ComponentTypeEnum.findByParamName(containerComponentType), null); - + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, + ComponentTypeEnum.findByParamName(containerComponentType), null); boolean failed = false; try { lockComponent(containerComponent, "batchDeleteComponentInstance"); for (String eachInstanceId : componentInstanceIdList) { - Either actionResponse = batchDeleteComponentInstance( - containerComponent, containerComponentType, eachInstanceId); + Either actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType, + eachInstanceId); log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse); if (actionResponse.isRight()) { log.error("Failed to delete ComponentInstance [{}]", eachInstanceId); @@ -3555,27 +3428,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { //sending the ids of the error nodes that were not deleted to UI deleteErrorMap.put("deleteFailedIds", deleteErrorIds); return deleteErrorMap; - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { unlockComponent(failed, containerComponent); } } - private Either batchDeleteComponentInstance(Component containerComponent, - String containerComponentType, + private Either batchDeleteComponentInstance(Component containerComponent, String containerComponentType, String componentInstanceId) { - ComponentInstance resultOp; final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - try { resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum); log.info("Successfully deleted instance with id {}", componentInstanceId); return Either.left(resultOp); - } - catch (ComponentException e){ + } catch (ComponentException e) { log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId); return Either.right(new ResponseFormat()); } @@ -3585,5 +3454,4 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { final User user = userValidations.validateUserExists(userId); userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java index e32c51f7da..e73ade119e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java @@ -18,7 +18,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; @@ -59,163 +58,125 @@ import org.springframework.beans.factory.annotation.Autowired; @org.springframework.stereotype.Component("componentInterfaceOperationBusinessLogic") public class ComponentInterfaceOperationBusinessLogic extends BaseBusinessLogic { + private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationBusinessLogic.class); private final ComponentValidations componentValidations; - private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationBusinessLogic .class); - @Autowired - public ComponentInterfaceOperationBusinessLogic(final IElementOperation elementDao, - final IGroupOperation groupOperation, + public ComponentInterfaceOperationBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation, final IGroupInstanceOperation groupInstanceOperation, - final IGroupTypeOperation groupTypeOperation, - final InterfaceOperation interfaceOperation, + final IGroupTypeOperation groupTypeOperation, final InterfaceOperation interfaceOperation, final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, final ArtifactsOperations artifactToscaOperation, final ComponentValidations componentValidations) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, - interfaceLifecycleTypeOperation, artifactToscaOperation); + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.componentValidations = componentValidations; } - public Optional updateComponentInstanceInterfaceOperation(final String componentId, - final String componentInstanceId, + public Optional updateComponentInstanceInterfaceOperation(final String componentId, final String componentInstanceId, final InterfaceDefinition interfaceDefinition, final ComponentTypeEnum componentTypeEnum, - final Wrapper errorWrapper, - final boolean shouldLock) + final Wrapper errorWrapper, final boolean shouldLock) throws BusinessLogicException { - final Component component = getComponent(componentId); - final Optional componentInstanceOptional = componentValidations - .getComponentInstance(component, componentInstanceId); + final Optional componentInstanceOptional = componentValidations.getComponentInstance(component, componentInstanceId); ResponseFormat responseFormat; if (componentInstanceOptional.isEmpty()) { responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); - LOGGER.debug("Failed to found component instance with id {}, error: {}", - componentInstanceId, responseFormat); + LOGGER.debug("Failed to found component instance with id {}, error: {}", componentInstanceId, responseFormat); errorWrapper.setInnerElement(responseFormat); return Optional.empty(); } - - Map> componentInstancesInterfaceMap = component - .getComponentInstancesInterfaces(); + Map> componentInstancesInterfaceMap = component.getComponentInstancesInterfaces(); if (MapUtils.isEmpty(componentInstancesInterfaceMap)) { componentInstancesInterfaceMap = new HashMap<>(); component.setComponentInstancesInterfaces(componentInstancesInterfaceMap); } - final List componentInstanceInterfaceList = componentInstancesInterfaceMap - .get(componentInstanceId); - + final List componentInstanceInterfaceList = componentInstancesInterfaceMap.get(componentInstanceId); if (CollectionUtils.isEmpty(componentInstanceInterfaceList)) { responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); - LOGGER.debug("Failed to found component instance with id {}, error: {}", - componentInstanceId, responseFormat); + LOGGER.debug("Failed to found component instance with id {}, error: {}", componentInstanceId, responseFormat); errorWrapper.setInnerElement(responseFormat); return Optional.empty(); } - - final Optional optionalOperationDataDefinition = interfaceDefinition - .getOperations().values().stream().findFirst(); + final Optional optionalOperationDataDefinition = interfaceDefinition.getOperations().values().stream().findFirst(); if (optionalOperationDataDefinition.isEmpty()) { responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND); - LOGGER.debug("Failed to found interface operation on component instance with id {}, error: {}", - componentInstanceId, responseFormat); + LOGGER.debug("Failed to found interface operation on component instance with id {}, error: {}", componentInstanceId, responseFormat); errorWrapper.setInnerElement(responseFormat); return Optional.empty(); } final OperationDataDefinition updatedOperationDataDefinition = optionalOperationDataDefinition.get(); - final Optional optionalComponentInstanceInterface = componentInstanceInterfaceList - .stream().filter(ci -> ci.getOperations().values().stream().anyMatch(operationDataDefinition -> - operationDataDefinition.getUniqueId() - .equalsIgnoreCase(updatedOperationDataDefinition.getUniqueId()))).findFirst(); - + final Optional optionalComponentInstanceInterface = componentInstanceInterfaceList.stream().filter( + ci -> ci.getOperations().values().stream().anyMatch( + operationDataDefinition -> operationDataDefinition.getUniqueId().equalsIgnoreCase(updatedOperationDataDefinition.getUniqueId()))) + .findFirst(); if (optionalComponentInstanceInterface.isEmpty()) { responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT); - LOGGER.debug("Failed to found ComponentInstanceInterface on component instance with id {}, error: {}", - componentInstanceId, responseFormat); + LOGGER + .debug("Failed to found ComponentInstanceInterface on component instance with id {}, error: {}", componentInstanceId, responseFormat); errorWrapper.setInnerElement(responseFormat); return Optional.empty(); } - updateOperationDefinitionImplementation(updatedOperationDataDefinition); - - optionalComponentInstanceInterface.get().getOperations() - .replace(updatedOperationDataDefinition.getName(), updatedOperationDataDefinition); - + optionalComponentInstanceInterface.get().getOperations().replace(updatedOperationDataDefinition.getName(), updatedOperationDataDefinition); boolean wasLocked = false; try { if (shouldLock) { lockComponent(componentId, component, "Update Interface Operation on Component instance"); wasLocked = true; } - - final StorageOperationStatus status = toscaOperationFacade - .updateComponentInstanceInterfaces(component, componentInstanceId); - + final StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceInterfaces(component, componentInstanceId); if (status != StorageOperationStatus.OK) { janusGraphDao.rollback(); - responseFormat = componentsUtils - .getResponseFormat(ActionStatus.GENERAL_ERROR); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); LOGGER.error("Exception occurred when updating Component Instance Interfaces {}", responseFormat); errorWrapper.setInnerElement(responseFormat); return Optional.empty(); } - final ComponentParametersView componentFilter = new ComponentParametersView(); componentFilter.disableAll(); componentFilter.setIgnoreUsers(false); componentFilter.setIgnoreComponentInstances(false); componentFilter.setIgnoreInterfaces(false); componentFilter.setIgnoreComponentInstancesInterfaces(false); - final Either operationStatusEither = toscaOperationFacade .updateComponentInstanceMetadataOfTopologyTemplate(component, componentFilter); - if (operationStatusEither.isRight()) { janusGraphDao.rollback(); - responseFormat = componentsUtils - .getResponseFormat(ActionStatus.GENERAL_ERROR); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); LOGGER.error("Exception occurred when updating Component Instance Topology template {}", responseFormat); errorWrapper.setInnerElement(responseFormat); return Optional.empty(); } janusGraphDao.commit(); - } catch (final Exception e) { janusGraphDao.rollback(); - LOGGER.error("Exception occurred when updating Interface Operation on Component Instance: {}", - e.getMessage(), e); + LOGGER.error("Exception occurred when updating Interface Operation on Component Instance: {}", e.getMessage(), e); responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); errorWrapper.setInnerElement(responseFormat); throw new BusinessLogicException(responseFormat); - } finally { if (wasLocked) { unlockComponent(component.getUniqueId(), componentTypeEnum); } } - return componentInstanceOptional; - } public User validateUser(final String userId) { final User user = userValidations.validateUserExists(userId); - userValidations - .validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); + userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); return user; } - private void unlockComponent(final String componentUniqueId, - final ComponentTypeEnum componentType) { + private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) { graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType()); } private void updateOperationDefinitionImplementation(final OperationDataDefinition updatedOperationDataDefinition) { final ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition(); - artifactInfo.setArtifactName( - String.format("'%s'", updatedOperationDataDefinition.getImplementation().getArtifactName()) - ); + artifactInfo.setArtifactName(String.format("'%s'", updatedOperationDataDefinition.getImplementation().getArtifactName())); updatedOperationDataDefinition.setImplementation(artifactInfo); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java index 5358cf5be4..c7fb395db1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -28,9 +27,8 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; import org.openecomp.sdc.common.log.wrappers.Logger; - @org.springframework.stereotype.Component -public class ComponentLocker { +public class ComponentLocker { private static final Logger log = Logger.getLogger(ComponentLocker.class.getName()); private final GraphLockOperation graphLockOperation; @@ -55,7 +53,7 @@ public class ComponentLocker { log.debug("#doLockComponent - locking component {} of type {}", id, nodeTypeEnum); StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(id, nodeTypeEnum); if (storageOperationStatus != StorageOperationStatus.OK) { - log.debug("#doLockComponent - failed to lock component {} with status {}", id, storageOperationStatus); + log.debug("#doLockComponent - failed to lock component {} with status {}", id, storageOperationStatus); throw new StorageException(storageOperationStatus); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java index f547dcf19c..e5bb817d98 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR; @@ -59,32 +58,25 @@ import org.springframework.beans.factory.annotation.Autowired; public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { private static final Logger LOGGER = Logger.getLogger(ComponentNodeFilterBusinessLogic.class.getName()); - private final NodeFilterOperation nodeFilterOperation; private final NodeFilterValidator nodeFilterValidator; @Autowired - public ComponentNodeFilterBusinessLogic(final IElementOperation elementDao, - final IGroupOperation groupOperation, - final IGroupInstanceOperation groupInstanceOperation, - final IGroupTypeOperation groupTypeOperation, + public ComponentNodeFilterBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation, + final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation, final InterfaceOperation interfaceOperation, final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - final ArtifactsOperations artifactToscaOperation, - final NodeFilterOperation nodeFilterOperation, + final ArtifactsOperations artifactToscaOperation, final NodeFilterOperation nodeFilterOperation, final NodeFilterValidator nodeFilterValidator) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, - interfaceLifecycleTypeOperation, artifactToscaOperation); + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.nodeFilterOperation = nodeFilterOperation; this.nodeFilterValidator = nodeFilterValidator; } - public Optional createNodeFilterIfNotExist(final String componentId, - final String componentInstanceId, - final boolean shouldLock, - final ComponentTypeEnum componentTypeEnum) + public Optional createNodeFilterIfNotExist(final String componentId, final String componentInstanceId, + final boolean shouldLock, final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException { - final Component component = getComponent(componentId); final Optional componentInstance = getComponentInstance(componentInstanceId, component); Optional filterDataDefinition = getCiNodeFilterDataDefinition(componentInstance); @@ -95,28 +87,24 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { boolean wasLocked = false; try { if (shouldLock) { - lockComponent(component.getUniqueId(), component,"Create Node Filter on component"); + lockComponent(component.getUniqueId(), component, "Create Node Filter on component"); wasLocked = true; } result = nodeFilterOperation.createNodeFilter(componentId, componentInstanceId); if (result.isRight()) { janusGraphDao.rollback(); - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Failed to Create Node filter on component with id {}", componentId); - throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(result.right().value()), component.getSystemName())); + LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to Create Node filter on component with id {}", componentId); + throw new BusinessLogicException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName())); } else { filterDataDefinition = Optional.ofNullable(result.left().value()); } janusGraphDao.commit(); LOGGER.debug("Node filter successfully created in component {} . ", component.getSystemName()); - } catch (final Exception e) { janusGraphDao.rollback(); - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Exception occurred during add Component node filter property values: {}", e.getMessage(), e); + LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during add Component node filter property values: {}", e.getMessage(), e); throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { if (wasLocked) { unlockComponent(component.getUniqueId(), componentTypeEnum); @@ -125,41 +113,32 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { return filterDataDefinition; } - public Optional deleteNodeFilterIfExists(final String componentId, - final String componentInstanceId, - final boolean shouldLock, - final ComponentTypeEnum componentTypeEnum) - throws BusinessLogicException { - + public Optional deleteNodeFilterIfExists(final String componentId, final String componentInstanceId, final boolean shouldLock, + final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException { final Component component = getComponent(componentId); - final Optional nodeFilterDataDefinition = - getCiNodeFilterDataDefinition(componentInstanceId, component); + final Optional nodeFilterDataDefinition = getCiNodeFilterDataDefinition(componentInstanceId, component); if (!nodeFilterDataDefinition.isPresent()) { return Optional.ofNullable(componentInstanceId); } - final Either result; boolean wasLocked = false; try { if (shouldLock) { - lockComponent(component.getUniqueId(), component,"Delete Node Filter from component"); + lockComponent(component.getUniqueId(), component, "Delete Node Filter from component"); wasLocked = true; } result = nodeFilterOperation.deleteNodeFilter(component, componentInstanceId); if (result.isRight()) { - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Failed to delete node filter in component {}. Response is {}. ", component.getName(), + LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to delete node filter in component {}. Response is {}. ", component.getName(), result.right().value()); janusGraphDao.rollback(); - throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(result.right().value()), component.getSystemName())); + throw new BusinessLogicException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName())); } janusGraphDao.commit(); LOGGER.debug("Node filter successfully deleted in component {} . ", component.getSystemName()); - } catch (final Exception e) { - LOGGER.error(BUSINESS_PROCESS_ERROR,"Exception occurred during delete deleting node filter: {}", - e.getMessage(), e); + LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete deleting node filter: {}", e.getMessage(), e); janusGraphDao.rollback(); throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { @@ -170,50 +149,39 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { return Optional.ofNullable(result.left().value()); } - public Optional addNodeFilter(final String componentId, - final String componentInstanceId, - final NodeFilterConstraintAction action, - final String propertyName, - final String constraint, - final boolean shouldLock, + public Optional addNodeFilter(final String componentId, final String componentInstanceId, + final NodeFilterConstraintAction action, final String propertyName, + final String constraint, final boolean shouldLock, final ComponentTypeEnum componentTypeEnum, - final NodeFilterConstraintType nodeFilterConstraintType, - final String capabilityName) + final NodeFilterConstraintType nodeFilterConstraintType, final String capabilityName) throws BusinessLogicException { - final Component component = getComponent(componentId); - CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId, - action, constraint, component, nodeFilterConstraintType); + CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint, + component, nodeFilterConstraintType); boolean wasLocked = false; try { if (shouldLock) { - lockComponent(component.getUniqueId(), component,"Add Node Filter on Component"); + lockComponent(component.getUniqueId(), component, "Add Node Filter on Component"); wasLocked = true; } - final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition = - new RequirementNodeFilterPropertyDataDefinition(); + final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition = new RequirementNodeFilterPropertyDataDefinition(); requirementNodeFilterPropertyDataDefinition.setName(propertyName); requirementNodeFilterPropertyDataDefinition.setConstraints(Collections.singletonList(constraint)); - - final Either result = addNewNodeFilter(componentId, - componentInstanceId, nodeFilterConstraintType, nodeFilterDataDefinition, - requirementNodeFilterPropertyDataDefinition, capabilityName); + final Either result = addNewNodeFilter(componentId, componentInstanceId, + nodeFilterConstraintType, nodeFilterDataDefinition, requirementNodeFilterPropertyDataDefinition, capabilityName); if (result.isRight()) { janusGraphDao.rollback(); - throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(result.right().value()), component.getSystemName())); + throw new BusinessLogicException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName())); } else { nodeFilterDataDefinition = result.left().value(); } janusGraphDao.commit(); LOGGER.debug("Node filter successfully created in component {} . ", component.getSystemName()); - } catch (final Exception e) { janusGraphDao.rollback(); - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Exception occurred during add component node filter property values: {}", e.getMessage(), e); + LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during add component node filter property values: {}", e.getMessage(), e); throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { if (wasLocked) { unlockComponent(component.getUniqueId(), componentTypeEnum); @@ -222,44 +190,35 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { return Optional.ofNullable(nodeFilterDataDefinition); } - public Optional deleteNodeFilter(final String componentId, - final String componentInstanceId, - final NodeFilterConstraintAction action, - final String constraint, - final int position, - final boolean shouldLock, - final ComponentTypeEnum componentTypeEnum, + public Optional deleteNodeFilter(final String componentId, final String componentInstanceId, + final NodeFilterConstraintAction action, final String constraint, final int position, + final boolean shouldLock, final ComponentTypeEnum componentTypeEnum, final NodeFilterConstraintType nodeFilterConstraintType) throws BusinessLogicException { - final Component component = getComponent(componentId); - CINodeFilterDataDefinition nodeFilterDataDefinition = - validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint, component, nodeFilterConstraintType); + CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint, + component, nodeFilterConstraintType); boolean wasLocked = false; try { if (shouldLock) { - lockComponent(component.getUniqueId(), component,"Add Node Filter on Component"); + lockComponent(component.getUniqueId(), component, "Add Node Filter on Component"); wasLocked = true; } final Either result = nodeFilterOperation - .deleteConstraint(componentId, componentInstanceId, nodeFilterDataDefinition, position, - nodeFilterConstraintType); + .deleteConstraint(componentId, componentInstanceId, nodeFilterDataDefinition, position, nodeFilterConstraintType); if (result.isRight()) { janusGraphDao.rollback(); - throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(result.right().value()), component.getSystemName())); + throw new BusinessLogicException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName())); } else { nodeFilterDataDefinition = result.left().value(); } janusGraphDao.commit(); LOGGER.debug("Node filter successfully deleted in component {} . ", component.getSystemName()); - } catch (final Exception e) { janusGraphDao.rollback(); - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Exception occurred during delete component node filter property values: {}", e.getMessage(), e); + LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete component node filter property values: {}", e.getMessage(), e); throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { if (wasLocked) { unlockComponent(component.getUniqueId(), componentTypeEnum); @@ -268,33 +227,26 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { return Optional.ofNullable(nodeFilterDataDefinition); } - private Either addNewNodeFilter( - final String componentId, - final String componentInstanceId, - final NodeFilterConstraintType nodeFilterConstraintType, - final CINodeFilterDataDefinition nodeFilterDataDefinition, - final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, - final String capabilityName) { - + private Either addNewNodeFilter(final String componentId, final String componentInstanceId, + final NodeFilterConstraintType nodeFilterConstraintType, + final CINodeFilterDataDefinition nodeFilterDataDefinition, + final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, + final String capabilityName) { if (NodeFilterConstraintType.PROPERTIES.equals(nodeFilterConstraintType)) { - return nodeFilterOperation.addNewProperty(componentId, componentInstanceId, nodeFilterDataDefinition, - requirementNodeFilterPropertyDataDefinition); + return nodeFilterOperation + .addNewProperty(componentId, componentInstanceId, nodeFilterDataDefinition, requirementNodeFilterPropertyDataDefinition); } - final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition = - new RequirementNodeFilterCapabilityDataDefinition(); + final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition = new RequirementNodeFilterCapabilityDataDefinition(); requirementNodeFilterCapabilityDataDefinition.setName(capabilityName); - final ListDataDefinition - propertyDataDefinitionListDataDefinition = new ListDataDefinition<>(); - propertyDataDefinitionListDataDefinition.getListToscaDataDefinition().addAll( - Collections.singleton(requirementNodeFilterPropertyDataDefinition)); + final ListDataDefinition propertyDataDefinitionListDataDefinition = new ListDataDefinition<>(); + propertyDataDefinitionListDataDefinition.getListToscaDataDefinition() + .addAll(Collections.singleton(requirementNodeFilterPropertyDataDefinition)); requirementNodeFilterCapabilityDataDefinition.setProperties(propertyDataDefinitionListDataDefinition); - return nodeFilterOperation.addNewCapabilities(componentId, componentInstanceId, nodeFilterDataDefinition, - requirementNodeFilterCapabilityDataDefinition); + return nodeFilterOperation + .addNewCapabilities(componentId, componentInstanceId, nodeFilterDataDefinition, requirementNodeFilterCapabilityDataDefinition); } - - private void unlockComponent(final String componentUniqueId, - final ComponentTypeEnum componentType) { + private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) { graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType()); } @@ -304,29 +256,23 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { return user; } - private Optional getComponentInstance(final String componentInstanceId, - final Component component) { + private Optional getComponentInstance(final String componentInstanceId, final Component component) { return component.getComponentInstanceById(componentInstanceId); } - private Optional getCiNodeFilterDataDefinition( - final Optional componentInstance) { - + private Optional getCiNodeFilterDataDefinition(final Optional componentInstance) { if (componentInstance.isPresent()) { return Optional.ofNullable(componentInstance.get().getNodeFilter()); } return Optional.empty(); } - private Optional getCiNodeFilterDataDefinition(final String componentInstanceId, - final Component component) + private Optional getCiNodeFilterDataDefinition(final String componentInstanceId, final Component component) throws BusinessLogicException { - - final Either response = nodeFilterValidator - .validateComponentInstanceExist(component, componentInstanceId); + final Either response = nodeFilterValidator.validateComponentInstanceExist(component, componentInstanceId); if (response.isRight()) { - throw new BusinessLogicException(componentsUtils - .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); + throw new BusinessLogicException( + componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); } final Optional componentInstance = getComponentInstance(componentInstanceId, component); if (componentInstance.isPresent()) { @@ -336,55 +282,40 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { } private CINodeFilterDataDefinition validateAndReturnNodeFilterDefinition(final String componentInstanceId, - final NodeFilterConstraintAction action, - final String constraint, + final NodeFilterConstraintAction action, final String constraint, final Component component, final NodeFilterConstraintType nodeFilterConstraintType) throws BusinessLogicException { - validateNodeFilter(component, componentInstanceId, action, constraint, nodeFilterConstraintType); - final Optional cINodeFilterDataDefinition = getCiNodeFilterDataDefinition( - componentInstanceId, component); + final Optional cINodeFilterDataDefinition = getCiNodeFilterDataDefinition(componentInstanceId, component); if (!cINodeFilterDataDefinition.isPresent()) { throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); } return cINodeFilterDataDefinition.get(); } - private void validateNodeFilter(final Component component, - final String componentInstanceId, - final NodeFilterConstraintAction action, - final String constraint, - final NodeFilterConstraintType nodeFilterConstraintType) throws BusinessLogicException { + private void validateNodeFilter(final Component component, final String componentInstanceId, final NodeFilterConstraintAction action, + final String constraint, final NodeFilterConstraintType nodeFilterConstraintType) throws BusinessLogicException { final Either response = nodeFilterValidator .validateFilter(component, componentInstanceId, Collections.singletonList(constraint), action, nodeFilterConstraintType); if (response.isRight()) { - throw new BusinessLogicException(componentsUtils - .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); + throw new BusinessLogicException( + componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); } } - public Optional updateNodeFilter(final String componentId, - final String componentInstanceId, - final UIConstraint uiConstraint, - final ComponentTypeEnum componentTypeEnum, - final NodeFilterConstraintType nodeFilterConstraintType, - final int index) + public Optional updateNodeFilter(final String componentId, final String componentInstanceId, + final UIConstraint uiConstraint, final ComponentTypeEnum componentTypeEnum, + final NodeFilterConstraintType nodeFilterConstraintType, final int index) throws BusinessLogicException { - - final Optional deleteActionResponse = deleteNodeFilter(componentId, - componentInstanceId, - NodeFilterConstraintAction.DELETE, null, index, true, componentTypeEnum, - nodeFilterConstraintType); - + final Optional deleteActionResponse = deleteNodeFilter(componentId, componentInstanceId, + NodeFilterConstraintAction.DELETE, null, index, true, componentTypeEnum, nodeFilterConstraintType); if (!deleteActionResponse.isPresent()) { - throw new BusinessLogicException(componentsUtils - .getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to delete node filter capabilities")); + throw new BusinessLogicException( + componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to delete node filter capabilities")); } - - return addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD, - uiConstraint.getServicePropertyName(), new ConstraintConvertor().convert(uiConstraint), true, - componentTypeEnum, nodeFilterConstraintType, + return addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD, uiConstraint.getServicePropertyName(), + new ConstraintConvertor().convert(uiConstraint), true, componentTypeEnum, nodeFilterConstraintType, StringUtils.isEmpty(uiConstraint.getCapabilityName()) ? "" : uiConstraint.getCapabilityName()); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java index 0f55ddfff1..c88746347e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.be.dao.api.ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND; @@ -55,31 +54,26 @@ import org.springframework.beans.factory.annotation.Autowired; public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic { private static final Logger LOGGER = Logger.getLogger(ComponentSubstitutionFilterBusinessLogic.class); - private final SubstitutionFilterOperation substitutionFilterOperation; private final NodeFilterValidator nodeFilterValidator; @Autowired - public ComponentSubstitutionFilterBusinessLogic(final IElementOperation elementDao, - final IGroupOperation groupOperation, + public ComponentSubstitutionFilterBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation, final IGroupInstanceOperation groupInstanceOperation, - final IGroupTypeOperation groupTypeOperation, - final InterfaceOperation interfaceOperation, + final IGroupTypeOperation groupTypeOperation, final InterfaceOperation interfaceOperation, final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, final ArtifactsOperations artifactToscaOperation, final SubstitutionFilterOperation substitutionFilterOperation, final NodeFilterValidator nodeFilterValidator) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, - interfaceLifecycleTypeOperation, artifactToscaOperation); + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.substitutionFilterOperation = substitutionFilterOperation; this.nodeFilterValidator = nodeFilterValidator; } - public Optional createSubstitutionFilterIfNotExist(final String componentId, - final boolean shouldLock, + public Optional createSubstitutionFilterIfNotExist(final String componentId, final boolean shouldLock, final ComponentTypeEnum componentTypeEnum) - throws BusinessLogicException { - + throws BusinessLogicException { final Component component = getComponent(componentId); Optional substitutionFilterDataDefinition = Optional.ofNullable(component.getSubstitutionFilter()); if (substitutionFilterDataDefinition.isPresent()) { @@ -92,13 +86,12 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic wasLocked = true; } final Either result = substitutionFilterOperation - .createSubstitutionFilter(componentId); + .createSubstitutionFilter(componentId); if (result.isRight()) { janusGraphDao.rollback(); - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Failed to Create Substitution filter on component with id {}", componentId); - throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(result.right().value()), component.getSystemName())); + LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to Create Substitution filter on component with id {}", componentId); + throw new BusinessLogicException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName())); } substitutionFilterDataDefinition = Optional.ofNullable(result.left().value()); component.setSubstitutionFilter(substitutionFilterDataDefinition.get()); @@ -106,87 +99,69 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic LOGGER.debug("Substitution filter successfully created in component {} . ", component.getSystemName()); } catch (final Exception e) { janusGraphDao.rollback(); - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Exception occurred during add Component Substitution filter property values: {}", e.getMessage(), e); + LOGGER + .error(BUSINESS_PROCESS_ERROR, "Exception occurred during add Component Substitution filter property values: {}", e.getMessage(), e); throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { if (wasLocked) { unlockComponent(component.getUniqueId(), componentTypeEnum); } } - return substitutionFilterDataDefinition; } - public Optional addSubstitutionFilter(final String componentId, - final String propertyName, - final String constraint, - final boolean shouldLock, - final ComponentTypeEnum componentTypeEnum) - throws BusinessLogicException { - + public Optional addSubstitutionFilter(final String componentId, final String propertyName, + final String constraint, final boolean shouldLock, + final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException { final Component component = getComponent(componentId); - final Either response = nodeFilterValidator - .validateComponentFilter(component, Collections.singletonList(constraint), NodeFilterConstraintAction.ADD); + .validateComponentFilter(component, Collections.singletonList(constraint), NodeFilterConstraintAction.ADD); if (response.isRight()) { - throw new BusinessLogicException(componentsUtils - .getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); + throw new BusinessLogicException( + componentsUtils.getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); } - boolean wasLocked = false; try { if (shouldLock) { lockComponent(component.getUniqueId(), component, "Add Substitution Filter on Component"); wasLocked = true; } - final RequirementSubstitutionFilterPropertyDataDefinition newProperty = - new RequirementSubstitutionFilterPropertyDataDefinition(); + final RequirementSubstitutionFilterPropertyDataDefinition newProperty = new RequirementSubstitutionFilterPropertyDataDefinition(); newProperty.setName(propertyName); newProperty.setConstraints(Collections.singletonList(constraint)); - final Either resultEither = - substitutionFilterOperation - .addPropertyFilter(componentId, component.getSubstitutionFilter(), newProperty); - + final Either resultEither = substitutionFilterOperation + .addPropertyFilter(componentId, component.getSubstitutionFilter(), newProperty); if (resultEither.isRight()) { janusGraphDao.rollback(); - throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(resultEither.right().value()), component.getSystemName())); + throw new BusinessLogicException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resultEither.right().value()), + component.getSystemName())); } - janusGraphDao.commit(); LOGGER.debug("Substitution filter successfully created in component {} . ", component.getSystemName()); return Optional.ofNullable(resultEither.left().value()); } catch (final Exception e) { janusGraphDao.rollback(); - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Exception occurred during add component substitution filter property values: {}", e.getMessage(), e); + LOGGER + .error(BUSINESS_PROCESS_ERROR, "Exception occurred during add component substitution filter property values: {}", e.getMessage(), e); throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { if (wasLocked) { unlockComponent(component.getUniqueId(), componentTypeEnum); } } - } - public Optional updateSubstitutionFilter(final String componentId, - final List constraints, - final boolean shouldLock, - final ComponentTypeEnum componentTypeEnum) + public Optional updateSubstitutionFilter(final String componentId, final List constraints, + final boolean shouldLock, final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException { - final Component component = getComponent(componentId); - final Either response = nodeFilterValidator - .validateComponentFilter(component, constraints, NodeFilterConstraintAction.UPDATE); + .validateComponentFilter(component, constraints, NodeFilterConstraintAction.UPDATE); if (response.isRight()) { - throw new BusinessLogicException(componentsUtils - .getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); + throw new BusinessLogicException( + componentsUtils.getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); } - SubstitutionFilterDataDefinition substitutionFilterDataDefinition = component.getSubstitutionFilter(); if (substitutionFilterDataDefinition == null) { throw new BusinessLogicException(componentsUtils.getResponseFormat(SUBSTITUTION_FILTER_NOT_FOUND)); @@ -198,26 +173,23 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic wasLocked = true; } final List properties = constraints.stream() - .map(this::getRequirementSubstitutionFilterPropertyDataDefinition).collect(Collectors.toList()); + .map(this::getRequirementSubstitutionFilterPropertyDataDefinition).collect(Collectors.toList()); final Either result = substitutionFilterOperation - .updateProperties(componentId, substitutionFilterDataDefinition, properties); - + .updateProperties(componentId, substitutionFilterDataDefinition, properties); if (result.isRight()) { janusGraphDao.rollback(); - throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(result.right().value()), component.getSystemName())); + throw new BusinessLogicException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName())); } else { substitutionFilterDataDefinition = result.left().value(); } janusGraphDao.commit(); LOGGER.debug("Substitution filter successfully updated in component {} . ", component.getSystemName()); - } catch (final Exception e) { janusGraphDao.rollback(); LOGGER.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), "Exception occurred during update component substitution filter property values: {}", e); throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { if (wasLocked) { unlockComponent(component.getUniqueId(), componentTypeEnum); @@ -226,39 +198,33 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic return Optional.ofNullable(substitutionFilterDataDefinition); } - public Optional deleteSubstitutionFilter(final String componentId, - final int position, - final boolean shouldLock, + public Optional deleteSubstitutionFilter(final String componentId, final int position, final boolean shouldLock, final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException { - final Component component = getComponent(componentId); SubstitutionFilterDataDefinition substitutionFilterDataDefinition = component.getSubstitutionFilter(); boolean wasLocked = false; try { if (shouldLock) { - lockComponent(component.getUniqueId(), component,"Delete substitution Filter on Component"); + lockComponent(component.getUniqueId(), component, "Delete substitution Filter on Component"); wasLocked = true; } final Either result = substitutionFilterOperation .deleteConstraint(componentId, substitutionFilterDataDefinition, position); if (result.isRight()) { janusGraphDao.rollback(); - throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(result.right().value()), component.getSystemName())); + throw new BusinessLogicException(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName())); } else { substitutionFilterDataDefinition = result.left().value(); } janusGraphDao.commit(); LOGGER.debug("Substitution filter successfully deleted in component {} . ", component.getSystemName()); - } catch (final Exception e) { janusGraphDao.rollback(); - LOGGER.error(BUSINESS_PROCESS_ERROR, - "Exception occurred during delete component substitution filter property values: {}", - e.getMessage(), e); + LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete component substitution filter property values: {}", e.getMessage(), + e); throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { if (wasLocked) { unlockComponent(component.getUniqueId(), componentTypeEnum); @@ -267,8 +233,7 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic return Optional.ofNullable(substitutionFilterDataDefinition); } - private void unlockComponent(final String componentUniqueId, - final ComponentTypeEnum componentType) { + private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) { graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType()); } @@ -278,11 +243,8 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic return user; } - private RequirementSubstitutionFilterPropertyDataDefinition getRequirementSubstitutionFilterPropertyDataDefinition( - final String constraint) { - - final RequirementSubstitutionFilterPropertyDataDefinition requirementSubstitutionFilterPropertyDataDefinition = - new RequirementSubstitutionFilterPropertyDataDefinition(); + private RequirementSubstitutionFilterPropertyDataDefinition getRequirementSubstitutionFilterPropertyDataDefinition(final String constraint) { + final RequirementSubstitutionFilterPropertyDataDefinition requirementSubstitutionFilterPropertyDataDefinition = new RequirementSubstitutionFilterPropertyDataDefinition(); requirementSubstitutionFilterPropertyDataDefinition.setConstraints(Arrays.asList(constraint)); return requirementSubstitutionFilterPropertyDataDefinition; } 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 20e796e1fa..645eb96253 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 @@ -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. @@ -19,9 +19,18 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Collection; +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 org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -34,26 +43,14 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Collection; -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 - * - * @author mshitrit * + * @author mshitrit */ @Component("compositionBusinessLogic") public class CompositionBusinessLogic { - private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + private static final Logger log = Logger.getLogger(CompositionBusinessLogic.class.getName()); private static final int VFC_CANVAS_ELEMENT_SIZE = 50; private static final int CP_CANVAS_ELEMENT_SIZE = 21; @@ -61,48 +58,48 @@ public class CompositionBusinessLogic { 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; + private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; @Autowired public CompositionBusinessLogic(ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; } - enum RelativePosition { - LEFT, RIGHT, UP, DOWN - }; - protected void setPositionsForComponentInstances(Resource resource, String userId) { - boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null - || resource.getComponentInstances().stream().anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())); - if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) { + boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null || resource.getComponentInstances().stream() + .anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())); + if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) { // Arrange Icons In Spiral Pattern - Map, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource); + Map, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances( + resource); // Set Relative Locations According to Canvas Size componentInstanceLocations.entrySet().forEach(this::setRelativePosition); // Update in DB - componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,resource, resource.getUniqueId(), - userId, resource.getComponentInstances(), false); + componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, resource.getUniqueId(), userId, + resource.getComponentInstances(), false); } } - + + ; + protected void setPositionsForComponentInstances(Service service, String userId) { - boolean isNotAllPositionsCalculated = service.getComponentInstances() == null - || service.getComponentInstances().stream().anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())); - if (isNotAllPositionsCalculated && service.getComponentInstances() != null) { + boolean isNotAllPositionsCalculated = service.getComponentInstances() == null || service.getComponentInstances().stream() + .anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())); + if (isNotAllPositionsCalculated && service.getComponentInstances() != null) { // Arrange Icons In Spiral Pattern - Map, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(service); + Map, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances( + service); // Set Relative Locations According to Canvas Size componentInstanceLocations.entrySet().forEach(this::setRelativePosition); // Update in DB - componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, service, service.getUniqueId(), - userId, service.getComponentInstances(), false); + componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, service, service.getUniqueId(), userId, + service.getComponentInstances(), false); } } 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)); @@ -113,67 +110,59 @@ public class CompositionBusinessLogic { final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS; double offsetedCanvasPosition; switch (componentInstance.getOriginType()) { - case CP: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0; - break; - case VL: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0; - break; - case VF: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0; - break; - case VFC: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0; - break; - case VFCMT: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0; - break; - default: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0; - break; + case CP: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0; + break; + case VL: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0; + break; + case VF: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0; + break; + case VFC: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0; + break; + case VFCMT: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0; + break; + default: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0; + break; } return String.valueOf(offsetedCanvasPosition); } protected Map, ComponentInstance> buildSpiralPatternPositioningForComponentInstances( - org.openecomp.sdc.be.model.Component component) { - + org.openecomp.sdc.be.model.Component component) { Map, ComponentInstance> componentInstanceLocations = new HashMap<>(); - List componentInstances = new ArrayList<>(); - if (component instanceof Resource){ + if (component instanceof Resource) { Resource resource = (Resource) component; List componentInstanceList = resource.getComponentInstances(); componentInstances.addAll(componentInstanceList); - }else if (component instanceof Service){ + } else if (component instanceof Service) { Service service = (Service) component; List componentInstanceList = service.getComponentInstances(); componentInstances.addAll(componentInstanceList); } - Map> connectededCps = getCpsConnectedToVFC(componentInstances, component); // Remove all cp that are connected from the list componentInstances.removeAll(connectededCps.values().stream().flatMap(Collection::stream).collect(Collectors.toList())); - buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances); buildCirclePatternForCps(componentInstanceLocations, connectededCps); - return componentInstanceLocations; } - protected void buildCirclePatternForCps(Map, ComponentInstance> componentInstLocations, Map> connectedCps) { - + protected void buildCirclePatternForCps(Map, ComponentInstance> componentInstLocations, + Map> connectedCps) { for (Entry> vfcCpList : connectedCps.entrySet()) { - componentInstLocations.entrySet().stream() - .filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())) - .findAny() - .ifPresent(vfcOfTheCps -> - buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), - componentInstLocations)); + componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny() + .ifPresent(vfcOfTheCps -> buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations)); } } - private void buildCirclePatternForOneGroupOfCps(ImmutablePair vfcLocation, List cpsGroup, Map, ComponentInstance> 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; @@ -185,10 +174,10 @@ public class CompositionBusinessLogic { componentInstLocations.put(new ImmutablePair<>(cpXposition, cpYposition), currCp); currentAngle += angleBetweenCps; } - } - private void buildSpiralPatternForMajorComponents(Map, ComponentInstance> componentInstanceLocations, List componentInstances) { + private void buildSpiralPatternForMajorComponents(Map, ComponentInstance> componentInstanceLocations, + List componentInstances) { int elementsCounter = 0; ImmutablePair currPlacement; ImmutablePair prevPlacement = null; @@ -203,30 +192,29 @@ public class CompositionBusinessLogic { } else { relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement); currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement); - } - componentInstanceLocations.put(currPlacement, curr); prevPlacement = currPlacement; } } - protected Map> getCpsConnectedToVFC(List allComponentInstances, org.openecomp.sdc.be.model.Component component) { + protected Map> getCpsConnectedToVFC(List allComponentInstances, + org.openecomp.sdc.be.model.Component component) { Map> vfcWithItsCps = new HashMap<>(); List allRelations = new ArrayList<>(); - if (component instanceof Resource){ + if (component instanceof Resource) { Resource vf = (Resource) component; allRelations = vf.getComponentInstancesRelations(); - }else if (component instanceof Service){ + } else if (component instanceof Service) { Service sv = (Service) component; allRelations = sv.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()); + 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); } @@ -234,18 +222,19 @@ public class CompositionBusinessLogic { return vfcWithItsCps; } - private void filterCpConnectedToVFC(List allComponentInstances, Map> vfcWithItsCps, ComponentInstance currCP, List connectedToTheCPList) { + 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()); - + 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 + // All instances connected to CP filter(p -> mateIds.contains(p.getUniqueId())). - // Filter in only VFC connected to the CP + // 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)) { @@ -259,37 +248,39 @@ public class CompositionBusinessLogic { } } - private RelativePosition getRelativePositionForCurrentElement(Map, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair prevPlacement) { + 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(); - } + 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) { - + private boolean isAdjacentElementOccupied(ImmutablePair currElement, RelativePosition adjacentElementRelationToCurrElement, + Map, ComponentInstance> allElements) { ImmutablePair adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement); return allElements.containsKey(adjacentElementPosition); } @@ -297,42 +288,42 @@ public class CompositionBusinessLogic { 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(); - } + 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; } + protected void validateAndSetDefaultCoordinates(ComponentInstance resourceInstance) { - int xCenter = CANVAS_WIDTH / 2; + int xCenter = CANVAS_WIDTH / 2; int yCenter = CANVAS_HEIGHT / 2; double leftLimit = -10D; double rightLimit = -1D; double generatedDouble = leftLimit + new SecureRandom().nextDouble() * (rightLimit - leftLimit); - - if (StringUtils.isEmpty(resourceInstance.getPosX())|| StringUtils.isEmpty(resourceInstance.getPosY())){ + if (StringUtils.isEmpty(resourceInstance.getPosX()) || StringUtils.isEmpty(resourceInstance.getPosY())) { resourceInstance.setPosX(calculateCompositionPosition(xCenter, generatedDouble, resourceInstance)); resourceInstance.setPosY(calculateCompositionPosition(yCenter, generatedDouble, resourceInstance)); - log.debug("Missing Failed PosX/PosY values. new values generated automatically. PosX = {} and PosY = {}", resourceInstance.getPosX(), resourceInstance.getPosY()); + log.debug("Missing Failed PosX/PosY values. new values generated automatically. PosX = {} and PosY = {}", resourceInstance.getPosX(), + resourceInstance.getPosY()); } } - + enum RelativePosition {LEFT, RIGHT, UP, DOWN} } 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 8b4c1c3e8b..4db24c1a25 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 @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.Date; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -45,8 +45,6 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.Date; - @Component("ConsumerBusinessLogic") public class ConsumerBusinessLogic extends BaseBusinessLogic { @@ -54,35 +52,26 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { private static final String CONSUMER_SALT = "Consumer salt"; private static final String CONSUMER_PW = "Consumer password"; private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response"; - + private static final Logger log = Logger.getLogger(ConsumerBusinessLogic.class.getName()); @javax.annotation.Resource private ConsumerOperation consumerOperation; - private static final Logger log = Logger.getLogger(ConsumerBusinessLogic.class.getName()); - @Autowired - public ConsumerBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public ConsumerBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); } 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); if (consumerValidationResponse.isRight()) { ResponseFormat responseFormat = consumerValidationResponse.right().value(); @@ -95,7 +84,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { 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); } @@ -104,15 +92,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { if (getResponse.isLeft() && getResponse.left().value() != null) { return updateConsumer(consumer); } - 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())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value())); componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); return Either.right(responseFormat); } @@ -127,7 +113,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { } 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); @@ -139,14 +124,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { User userFromDB; try { userFromDB = userAdmin.getUser(user.getUserId(), false); - }catch (ByActionStatusComponentException e){ + } catch (ByActionStatusComponentException e) { 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 = userFromDB; // validate user role log.debug("validate user role"); @@ -175,7 +159,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { return Either.right(validateEcompUserSalt.right().value()); } return Either.left(consumer); - } private Either validateConsumerName(ConsumerDefinition consumer) { @@ -190,13 +173,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { } 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))); + 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); } @@ -215,7 +198,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { log.debug("Consumer password is invalid."); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW)); } - return Either.left(consumer); } @@ -233,7 +215,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { log.debug("Consumer salt is invalid."); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT)); } - return Either.left(consumer); } @@ -299,7 +280,8 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { public Either updateConsumer(ConsumerDefinition consumer) { Either updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer)); if (updateResult.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value())); return Either.right(responseFormat); } consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition()); @@ -317,5 +299,4 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic { 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 1757fcdf01..fad72ccd14 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 @@ -17,20 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; 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; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.tosca.CsarUtils; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.GeneralUtility; -import org.openecomp.sdc.exception.ResponseFormat; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; @@ -43,11 +32,19 @@ import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import org.apache.commons.lang3.tuple.ImmutablePair; +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.impl.ComponentsUtils; +import org.openecomp.sdc.be.tosca.CsarUtils; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.exception.ResponseFormat; public class CsarValidationUtils { private static final Logger log = Logger.getLogger(CsarValidationUtils.class.getName()); - private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version"; private static final String CSAR_VERSION = "CSAR-Version"; private static final String CREATED_BY = "Created-By"; @@ -56,11 +53,10 @@ public class CsarValidationUtils { private static final String TOSCA_FILE = "TOSCA.meta"; private static final String DEL_PATTERN = "([/\\\\]+)"; private static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA + - // Artifact Group (i.e Deployment/Informational) - DEL_PATTERN + TOSCA_FILE; - + // Artifact Group (i.e Deployment/Informational) + DEL_PATTERN + TOSCA_FILE; private 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}; private static final String ARTIFACTS_METADATA_FILE = "HEAT.meta"; private static final String TOSCA_CSAR_EXTENSION = ".csar"; private static final String TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID = "TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}"; @@ -74,6 +70,7 @@ public class CsarValidationUtils { /** * Validates Csar + * * @param csar * @param csarUUID * @param componentsUtils @@ -84,9 +81,7 @@ public class CsarValidationUtils { 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()) { @@ -96,26 +91,25 @@ public class CsarValidationUtils { } 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 ){ + for (int i = 0; i < numberOfArtifacts; ++i) { collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove); } nonUniqueArtifactsToRemove.stream().forEach(csar::remove); } - private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List nonUniqueArtifactsToRemove) { - + 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 ){ + 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]); + 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]); } } @@ -130,158 +124,175 @@ public class CsarValidationUtils { String otherGroupType = otherParsedPath[artifactGroupTypeInd]; String otherArtifactName = otherParsedPath[artifactNameInd]; String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null; - - if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){ + if (artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)) { isEqualArtifactNames = vfcToscaName == null || vfcToscaName.equalsIgnoreCase(otherParsedPath[1]); } return isEqualArtifactNames; } - public static Either, ResponseFormat> getToscaYaml(Map csar, String csarUUID, ComponentsUtils componentsUtils) { + 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()){ + 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); + 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("\\","\\\\"))); + 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); + 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()){ + 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_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_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); + 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) ) { + 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_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_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); + 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)); + 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> getArtifactContent(String csarUUID, Map csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) { + public static Either, ResponseFormat> getArtifactContent(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_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID)); + BeEcompErrorManager.getInstance() + .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_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); + 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) { - + 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()){ + 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); + 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); + 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 blockStatus = validateBlock(csarUUID, splited, componentsUtils); if (blockStatus.isRight()) { return Either.right(blockStatus.right().value()); } - return Either.left(true); - } private static Either validateBlock(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); + 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); + 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); + 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)) && !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); + .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++; @@ -294,48 +305,45 @@ public class CsarValidationUtils { return floatMatcher.matches(); } - private static Either validateIsTOSCAMetadataExist(Map csar, String csarUUID, ComponentsUtils componentsUtils) { + 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()){ - + 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); + 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()); - 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); + 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) { return payloadName != null && payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java index 5af7cf660b..401222861b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; @@ -35,23 +37,15 @@ import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - @org.springframework.stereotype.Component("dataTypeBusinessLogic") public class DataTypeBusinessLogic extends BaseBusinessLogic { @Autowired - public DataTypeBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public DataTypeBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); } /** @@ -64,22 +58,19 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic { ComponentParametersView filter = new ComponentParametersView(); filter.disableAll(); filter.setIgnoreDataType(false); - // Get Component object - Either componentResult = - toscaOperationFacade.getToscaElement(componentId, filter); + Either componentResult = toscaOperationFacade.getToscaElement(componentId, filter); if (componentResult.isRight()) { return Either.right(componentResult.right().value()); } Component component = componentResult.left().value(); - List dataTypesToReturn = component.getDataTypes(); if (dataTypesToReturn == null) { // this means there is no DATA_TYPES graph vertex. + // in this case, returns empty list. dataTypesToReturn = new ArrayList<>(); } - return Either.left(dataTypesToReturn); } @@ -114,23 +105,19 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic { ComponentParametersView filter = new ComponentParametersView(); filter.disableAll(); filter.setIgnoreDataType(false); - // Get Component object - Either componentResult = - toscaOperationFacade.getToscaElement(componentId, filter); + Either componentResult = toscaOperationFacade.getToscaElement(componentId, filter); if (componentResult.isRight()) { // not exists return Either.right(componentResult.right().value()); } - return deletePrivateDataType(componentResult.left().value(), dataTypeName); } /** * Delete a data type from the Component. * - * @param component Component object which has data types. - * needs to be fetched with componentParametersView.setIgnoreDataType(false) + * @param component Component object which has data types. needs to be fetched with componentParametersView.setIgnoreDataType(false) * @param dataTypeName Data type name to be deleted * @return deleted data type */ @@ -140,18 +127,15 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic { if (CollectionUtils.isEmpty(dataTypes)) { return Either.right(StorageOperationStatus.NOT_FOUND); } - Optional dataTypeResult = - dataTypes.stream().filter(e -> e.getName().equals(dataTypeName)).findFirst(); + Optional dataTypeResult = dataTypes.stream().filter(e -> e.getName().equals(dataTypeName)).findFirst(); if (!dataTypeResult.isPresent()) { return Either.right(StorageOperationStatus.NOT_FOUND); } - // delete it StorageOperationStatus deleteResult = toscaOperationFacade.deleteDataTypeOfComponent(component, dataTypeName); if (deleteResult != StorageOperationStatus.OK) { return Either.right(deleteResult); } - // return deleted data type if ok return Either.left(dataTypeResult.get()); } 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 2e8344fc0a..4c7f072f71 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 @@ -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. @@ -17,10 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.Resource; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -36,14 +42,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; -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.stream.Collectors; - @Component("dataTypeImportManager") public class DataTypeImportManager { @@ -56,91 +54,90 @@ public class DataTypeImportManager { private CommonImportManager commonImportManager; public Either>, ResponseFormat> createDataTypes(String dataTypeYml) { - return commonImportManager.createElementTypes(dataTypeYml, this::createDataTypesFromYml, this::createDataTypesByDao, ElementTypeEnum.DATA_TYPE); + return commonImportManager + .createElementTypes(dataTypeYml, this::createDataTypesFromYml, this::createDataTypesByDao, ElementTypeEnum.DATA_TYPE); } private Either, ActionStatus> createDataTypesFromYml(String dataTypesYml) { return commonImportManager.createElementTypesFromYml(dataTypesYml, this::createDataType); } - private Either>, ResponseFormat> createDataTypesByDao(List dataTypesToCreate) { - - return commonImportManager.createElementTypesByDao(dataTypesToCreate, this::validateDataType, dataType -> new ImmutablePair<>(ElementTypeEnum.DATA_TYPE, dataType.getName()), - dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType)); + private Either>, ResponseFormat> createDataTypesByDao( + List dataTypesToCreate) { + return commonImportManager.createElementTypesByDao(dataTypesToCreate, this::validateDataType, + dataType -> new ImmutablePair<>(ElementTypeEnum.DATA_TYPE, 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); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); return Either.right(responseFormat); } } else { if (!ToscaPropertyType.isScalarType(dataTypeName) && isAbstract(derivedDataType)) { log.warn("Creating data type {} which derived from abstract data type with no properties", dataType.getName()); } - } + } } else { // properties tag cannot be empty if (properties.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null); - + 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(PropertyDataDefinition::getName).collect(Collectors.toSet()); if (collect != null && properties.size() != collect.size()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null); - + 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(PropertyDataDefinition::getName).collect(Collectors.toList()); + List propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())) + .map(PropertyDataDefinition::getName).collect(Collectors.toList()); if (propertiesWithSameTypeAsDataType != null && !propertiesWithSameTypeAsDataType.isEmpty()) { 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); - + 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); - + 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() && derivedDataTypeDef!=null) { - + if (properties != null && !properties.isEmpty() && derivedDataTypeDef != null) { if (isScalarType(derivedDataTypeDef)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null); - + 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(); @@ -151,18 +148,18 @@ public class DataTypeImportManager { } 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(PropertyDataDefinition::getName).collect(Collectors.toSet()); + Set alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())) + .map(PropertyDataDefinition::getName).collect(Collectors.toSet()); if (alreadyExistPropsCollection != null && !alreadyExistPropsCollection.isEmpty()) { List duplicateProps = new ArrayList<>(); duplicateProps.addAll(alreadyExistPropsCollection); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps); - + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps); return Either.right(responseFormat); } - } } } @@ -170,37 +167,27 @@ public class DataTypeImportManager { } private boolean isAbstract(String dataTypeName) { - ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); - return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract(); - } 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(); } - return isScalar; } private DataTypeDefinition createDataType(String dataTypeName, Map toscaJson) { DataTypeDefinition dataType = new DataTypeDefinition(); - dataType.setName(dataTypeName); - if (toscaJson != null) { // Description commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), dataType::setDescription); @@ -211,5 +198,4 @@ public class DataTypeImportManager { } return dataType; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java index cc831d4255..be61e7b112 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.Map; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; @@ -30,8 +30,6 @@ import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; -import java.util.Map; - @Component public class DataTypesService { @@ -46,14 +44,15 @@ public class DataTypesService { if (allDataTypes.isRight()) { JanusGraphOperationStatus operationStatus = allDataTypes.right().value(); if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInternalDataError("FetchDataTypes", "Data types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); } else { - BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInternalFlowError("FetchDataTypes", "Failed to fetch data types", BeEcompErrorManager.ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } } return Either.left(allDataTypes.left().value()); } - } 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 66cab35cd2..f3334e6177 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 @@ -17,11 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -45,44 +49,28 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - @Component("distributionMonitoringBusinessLogic") public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { - private static final String DEPLOYED = "Deployed"; + 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 = Logger.getLogger(ArtifactsBusinessLogic.class.getName()); - private final AuditCassandraDao cassandraDao; @Autowired - public DistributionMonitoringBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - AuditCassandraDao cassandraDao, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public DistributionMonitoringBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + AuditCassandraDao cassandraDao, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.cassandraDao = cassandraDao; } public Either getListOfDistributionStatus(String did, String userId) { - validateUserExists(userId); - log.trace("getListOfDistributionStatus for did {}", did); Either, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did); if (distributionStatus.isRight()) { @@ -96,7 +84,6 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent)); } } - DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse(); distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList); log.trace("list statuses for did {} is {} ", did, distribStatusInfoList); @@ -105,7 +92,6 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { public Either getListOfDistributionServiceStatus(String serviceUuid, String userId) { validateUserExists(userId); - log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid); Either, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid); if (status.isRight()) { @@ -134,15 +120,12 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { AuditingGenericEvent resAuditingGenericEvent = null; for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) { auditingGenericEvent.fillFields(); - String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_ACTION.getDisplayName()); Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName()); if (modifierUserId != null) { distributionStatusOfServiceInfo.setUserId((String) modifierUserId); } - if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) { - isResult = true; resAuditingGenericEvent = auditingGenericEvent; break; @@ -151,38 +134,34 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { } else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) { dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent); } - resAuditingGenericEvent = auditingGenericEvent; } - if (resAuditingGenericEvent != null) { Map fields = resAuditingGenericEvent.getFields(); - if (fields != null) { - Optional.ofNullable( - fields.get(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName())) + Optional.ofNullable(fields.get(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName())) .ifPresent(timestamp -> distributionStatusOfServiceInfo.setTimestamp((String) timestamp)); } } - 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))) + if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK))) { distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED); - else + } else { distributionStatusOfServiceInfo.setDeployementStatus(ERROR); + } } - } else + } else { distributionStatusOfServiceInfo.setDeployementStatus(ERROR); - } else + } + } else { distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED); + } reslist.add(distributionStatusOfServiceInfo); } - return reslist; } @@ -196,25 +175,21 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { } 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(AuditingFieldsKey.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); @@ -222,5 +197,4 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { } 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 631daefff8..499a6127a1 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 @@ -19,10 +19,26 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; +import static org.apache.commons.lang.BooleanUtils.isTrue; +import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.DEFAULT_ICON; + 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.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; @@ -89,24 +105,6 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -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.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import static org.apache.commons.lang.BooleanUtils.isTrue; -import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.DEFAULT_ICON; - @org.springframework.stereotype.Component("elementsBusinessLogic") public class ElementBusinessLogic extends BaseBusinessLogic { @@ -116,27 +114,21 @@ public class ElementBusinessLogic extends BaseBusinessLogic { private static final String VALIDATION_OF_USER_FAILED_USER_ID = "Validation of user failed, userId {}"; private static final String COMPONENT_TYPE_IS_INVALID = "Component type {} is invalid"; private static final String VALIDATION_OF_USER_ROLE_FAILED_USER_ID = "Validation of user role failed, userId {}"; - private final IElementOperation elementOperation; private final UserBusinessLogic userAdminManager; @Autowired - public ElementBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation, IElementOperation elementOperation, - UserBusinessLogic userAdminManager) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public ElementBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation, + IElementOperation elementOperation, UserBusinessLogic userAdminManager) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.elementOperation = elementOperation; this.userAdminManager = userAdminManager; } + /** - * * @param user * @return */ @@ -147,35 +139,29 @@ public class ElementBusinessLogic extends BaseBusinessLogic { String role = user.getRole(); String userId = user.getUserId(); Role currentRole = Role.valueOf(role); - switch (currentRole) { - case DESIGNER: - response = handleDesigner(userId); - break; - - case PRODUCT_STRATEGIST: - response = handleProductStrategist(); - break; - - case PRODUCT_MANAGER: - response = handleProductManager(userId); - break; - - case ADMIN: - response = handleAdmin(); - break; - - default: - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - break; + case DESIGNER: + response = handleDesigner(userId); + break; + case PRODUCT_STRATEGIST: + response = handleProductStrategist(); + break; + case PRODUCT_MANAGER: + 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) { - + private Either>, ResponseFormat> convertedToListResponse( + Either>, ResponseFormat> setResponse) { Map> arrayResponse = new HashMap<>(); if (setResponse.isLeft()) { for (Map.Entry> entry : setResponse.left().value().entrySet()) { @@ -228,13 +214,15 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return response; } - private Either>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set lifecycleStates, Set lastStateStates) { - + private Either>, ResponseFormat> getFollowedResourcesAndServices(String userId, + Set lifecycleStates, + Set lastStateStates) { try { - Either, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE); - + Either, StorageOperationStatus> resources = toscaOperationFacade + .getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE); if (resources.isLeft()) { - Either, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE); + Either, StorageOperationStatus> services = toscaOperationFacade + .getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE); if (services.isLeft()) { Map> result = new HashMap<>(); result.put(SERVICES, services.left().value()); @@ -251,8 +239,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } } - private Either>, ResponseFormat> getFollowedProducts(String userId, Set lifecycleStates, Set lastStateStates) { - Either, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT); + 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()); @@ -274,12 +264,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } 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 = validateUserExists(userId); if (category == null) { log.debug("Category json is invalid"); @@ -287,7 +275,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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; @@ -297,7 +284,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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_USER_ID, userId); @@ -305,35 +291,30 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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()); + 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()); + 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); - - if (ValidationUtils.validateCategoryIconNotEmpty(category.getIcons())){ + if (ValidationUtils.validateCategoryIconNotEmpty(category.getIcons())) { log.debug("createCategory: setting category icon to default icon since service category was created without an icon "); category.setIcons(Arrays.asList(DEFAULT_ICON)); } - 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); @@ -341,19 +322,19 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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); + 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); + 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())); } @@ -364,37 +345,33 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(category); } - public Either createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) { - + 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; - try{ - user = validateUserExists(userId); - } catch(ByActionStatusComponentException e){ + try { + user = validateUserExists(userId); + } catch (ByActionStatusComponentException e) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, - responseFormat); + handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, responseFormat); throw e; - } catch(ByResponseFormatComponentException e){ + } catch (ByResponseFormatComponentException e) { ResponseFormat responseFormat = e.getResponseFormat(); - handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, - responseFormat); + handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, responseFormat); throw e; } if (componentTypeEnum == null) { @@ -403,7 +380,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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"); @@ -411,7 +387,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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_USER_ID, userId); @@ -419,65 +394,69 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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); + 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()); + 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()); + 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); + 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); + 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); + 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); + 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()); @@ -488,18 +467,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic { if (subCategoryDefinition != null) { subCategoryName = subCategoryDefinition.getName(); } - subCategory.setName(subCategoryName); ///////////////////////////////////////////// Validations end - - Either createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType); + 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); @@ -507,25 +484,23 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(subCategoryCreated); } - private void handleComponentException(String userId, AuditingActionEnum auditingAction, String componentType, - String parentCategoryName, String origSubCategoryName, ResponseFormat responseFormat) { + private void handleComponentException(String userId, AuditingActionEnum auditingAction, String componentType, String parentCategoryName, + String origSubCategoryName, ResponseFormat responseFormat) { User user; log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId); user = new User(); user.setUserId(userId); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, - componentType); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); } - private void handleComponentException(GroupingDefinition grouping, String userId, AuditingActionEnum auditingAction, - String componentType, String parentCategoryName, String parentSubCategoryName, ResponseFormat responseFormat) { + private void handleComponentException(GroupingDefinition grouping, String userId, AuditingActionEnum auditingAction, String componentType, + String parentCategoryName, String parentSubCategoryName, ResponseFormat responseFormat) { User user; log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId); user = new User(); user.setUserId(userId); String groupingNameForAudit = grouping == null ? null : grouping.getName(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, - auditingAction, componentType); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType); } private void handleComponentException(String componentType, String userId, ResponseFormat responseFormat) { @@ -536,8 +511,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic { componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat); } - public Either createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) { - + 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(); @@ -545,41 +520,33 @@ public class ElementBusinessLogic extends BaseBusinessLogic { // For auditing String parentCategoryName = grandParentCategoryId; String parentSubCategoryName = parentSubCategoryId; - User user; - try{ + try { user = validateUserExists(userId); - } catch(ByResponseFormatComponentException e){ + } catch (ByResponseFormatComponentException e) { ResponseFormat responseFormat = e.getResponseFormat(); - handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, - parentSubCategoryName, - responseFormat); + handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, parentSubCategoryName, responseFormat); throw e; - } catch(ByActionStatusComponentException e){ + } catch (ByActionStatusComponentException e) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, - parentSubCategoryName, responseFormat); + handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, parentSubCategoryName, responseFormat); throw e; } - 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"); @@ -587,7 +554,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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_USER_ID, userId); @@ -595,78 +561,80 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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); + 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); + 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()); + 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()); + 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); + 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); + 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); + 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()) { @@ -679,10 +647,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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); @@ -690,16 +656,14 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, + componentType); return Either.left(groupingCreated); } - - public Either, ResponseFormat> getAllCategories(String componentType, String userId) { ResponseFormat responseFormat; User user = new User(); @@ -711,11 +675,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } try { user = validateUserExists(userId); - } catch (ByActionStatusComponentException e){ + } catch (ByActionStatusComponentException e) { responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); handleComponentException(componentType, userId, responseFormat); throw e; - } catch (ByResponseFormatComponentException e){ + } catch (ByResponseFormatComponentException e) { responseFormat = e.getResponseFormat(); handleComponentException(componentType, userId, responseFormat); throw e; @@ -727,7 +691,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat); return Either.right(responseFormat); } - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); Either, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false); if (getAllCategoriesByType.isRight()) { @@ -741,25 +704,22 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(categories); } - - public Either getAllCategories(String userId) { ResponseFormat responseFormat; UiCategories categories = new UiCategories(); - User user = validateUserExists(userId); - // GET resource categories - Either, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false); + Either, ActionStatus> getResourceCategoriesByType = elementOperation + .getAllCategories(NodeTypeEnum.ResourceNewCategory, false); if (getResourceCategoriesByType.isRight()) { responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value()); componentsUtils.auditGetCategoryHierarchy(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); + Either, ActionStatus> getServiceCategoriesByType = elementOperation + .getAllCategories(NodeTypeEnum.ServiceNewCategory, false); if (getServiceCategoriesByType.isRight()) { responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value()); componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.SERVICE.getValue(), responseFormat); @@ -771,17 +731,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } public Either deleteCategory(String categoryId, String componentTypeParamName, String userId) { - validateUserExists(userId); - 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... @@ -793,17 +749,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } public Either deleteSubCategory(String parentSubCategoryId, String componentTypeParamName, String userId) { - validateUserExists(userId); - 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... @@ -815,17 +767,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } public Either deleteGrouping(String groupingId, String componentTypeParamName, String userId) { - validateUserExists(userId); - 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... @@ -838,26 +786,31 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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 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); + 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 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 + // 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); @@ -866,14 +819,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private Either validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) { + 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(), ""); + responseFormat = componentsUtils + .getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), ""); } else { responseFormat = componentsUtils.getResponseFormat(actionStatus); } @@ -882,14 +837,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(categoryByTypeAndId.left().value()); } - private Either validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) { + 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(), ""); + responseFormat = componentsUtils + .getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), ""); } else { responseFormat = componentsUtils.getResponseFormat(actionStatus); } @@ -898,22 +855,24 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(subCategoryByTypeAndId.left().value()); } - private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) { + 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) { + 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) { + 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) { ActionStatus status = validateUserExistsActionStatus(userId); if (ActionStatus.OK != status) { @@ -942,19 +901,18 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return elementOperation.getDefaultHeatTimeout(); } - public Either>, ResponseFormat> getCatalogComponents(String userId, List excludeTypes) { + public Either>, ResponseFormat> getCatalogComponents(String userId, List excludeTypes) { try { return toscaOperationFacade.getCatalogOrArchiveComponents(true, excludeTypes) - .bimap(this::groupByComponentType, - err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err))); + .bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err))); } finally { janusGraphDao.commit(); } } private Map> groupByComponentType(List components) { - Map> map = components.stream().collect(Collectors.groupingBy(cmpt -> cmptTypeToString(cmpt.getComponentType()))); - + 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<>(); @@ -966,26 +924,26 @@ public class ElementBusinessLogic extends BaseBusinessLogic { private String cmptTypeToString(ComponentTypeEnum componentTypeEnum) { switch (componentTypeEnum) { - case RESOURCE: - return RESOURCES; - case SERVICE: - return SERVICES; - default: - throw new IllegalStateException("resources or services only"); + 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) { + 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())); + 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()) { @@ -993,38 +951,35 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } 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))); + 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 + + // 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) { + private Either, StorageOperationStatus> getFilteredComponents(Map filters, ComponentTypeEnum assetType, + boolean inTransaction) { Either, StorageOperationStatus> assetResult = Either.left(new LinkedList<>()); if (assetType == ComponentTypeEnum.RESOURCE) { - assetResult = getFilteredResources(filters, inTransaction); - } else if (assetType == ComponentTypeEnum.SERVICE) { - assetResult = getFilteredServices(filters, inTransaction); } return assetResult; } - private Either, StorageOperationStatus> getFilteredServices(Map filters, boolean inTransaction) { - + 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); @@ -1032,7 +987,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic { filters.remove(FilterKeyEnum.CATEGORY); return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); } - if (categoryName != null) { // primary filter components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, NodeTypeEnum.Service, inTransaction, null); if (components.isLeft() && distEnum != null) {// secondary filter @@ -1042,52 +996,44 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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); + 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()); } @@ -1135,13 +1081,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } public Either, StorageOperationStatus> getFilteredResources(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()) { @@ -1155,10 +1099,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic { if (!subCategoryData.isPresent()) { return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); } - return fetchByCategoryOrSubCategoryUid(subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.Resource, inTransaction, resourceType); + return fetchByCategoryOrSubCategoryUid(subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.Resource, inTransaction, + resourceType); } - - return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction, resourceType); + return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction, + resourceType); } if (subcategories != null) { return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); @@ -1167,12 +1112,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } private Either>, StorageOperationStatus> getAllSubCategories(String categoryName) { - Either categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); + Either categoryResult = elementOperation + .getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); if (categoryResult.isRight()) { return Either.right(categoryResult.right().value()); } CategoryData categoryData = categoryResult.left().value(); - Either>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); @@ -1182,12 +1127,17 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(childrenNodes.left().value()); } - private Optional> validateCategoryHierarcy(List> childNodes, String subCategoryName) { - Predicate> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName); + 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, boolean inTransaction, ResourceTypeEnum resourceType) { + protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, + NodeTypeEnum categoryType, + boolean inTransaction, + ResourceTypeEnum resourceType) { try { return collectComponents(categoryType, categoryUid, resourceType); } finally { @@ -1197,7 +1147,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } } - protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, NodeTypeEnum neededType, boolean inTransaction, ResourceTypeEnum resourceType) { + protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, + NodeTypeEnum categoryType, + NodeTypeEnum neededType, + boolean inTransaction, + ResourceTypeEnum resourceType) { List components = new ArrayList<>(); try { Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; @@ -1211,11 +1165,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic { Either, StorageOperationStatus> result = collectComponents(neededType, category.getUniqueId(), resourceType); if (result.isRight() && result.right().value() != StorageOperationStatus.NOT_FOUND) { return result; - } else if (result.isLeft()){ + } else if (result.isLeft()) { components.addAll(result.left().value()); } } - if (components.isEmpty()){ + if (components.isEmpty()) { return Either.right(StorageOperationStatus.NOT_FOUND); } return Either.left(components); @@ -1226,36 +1180,35 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } } - - private Either, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, ResourceTypeEnum resourceType) { + private Either, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, + ResourceTypeEnum resourceType) { List components = new ArrayList<>(); Either categoryVertexById = janusGraphDao.getVertexById(categoryUid, JsonParseFlagEnum.NoParse); - if (categoryVertexById.isRight()){ + if (categoryVertexById.isRight()) { JanusGraphOperationStatus status = categoryVertexById.right().value(); log.debug("#collectComponents Failed to get category vertex with uid {}, status is {}.", categoryUid, status); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } GraphVertex categoryVertex = categoryVertexById.left().value(); - Either, JanusGraphOperationStatus> componentsVertices = janusGraphDao.getParentVertices(categoryVertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.ParseMetadata); - if (componentsVertices.isRight()){ + Either, JanusGraphOperationStatus> componentsVertices = janusGraphDao + .getParentVertices(categoryVertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.ParseMetadata); + if (componentsVertices.isRight()) { JanusGraphOperationStatus status = componentsVertices.right().value(); log.debug("#collectComponents Failed to get components vertices of category {}, status is {}.", categoryVertex, status); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } - List componentsMetadataDataDefinition = componentsVertices.left().value() - .stream() - .filter(Objects::nonNull) - .filter(componentsVertex -> Objects.nonNull(componentsVertex.getType())) - .map(ModelConverter::convertToComponentMetadataDataDefinition) - .collect(Collectors.toList()); + List componentsMetadataDataDefinition = componentsVertices.left().value().stream().filter(Objects::nonNull) + .filter(componentsVertex -> Objects.nonNull(componentsVertex.getType())).map(ModelConverter::convertToComponentMetadataDataDefinition) + .collect(Collectors.toList()); for (ComponentMetadataDataDefinition component : componentsMetadataDataDefinition) { boolean isHighest = isTrue(component.isHighestVersion()); boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, component); boolean isDeleted = isTrue(component.isDeleted()); boolean isArchived = isTrue(component.isArchived()); if (isHighest && isMatchingResourceType && !isDeleted && !isArchived) { - Either result = toscaOperationFacade.getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (result.isRight()) { + Either result = toscaOperationFacade + .getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (result.isRight()) { return Either.right(result.right().value()); } components.add(result.left().value()); @@ -1264,8 +1217,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return Either.left(components); } - private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, ComponentMetadataDataDefinition componentData) { - + private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, + ComponentMetadataDataDefinition componentData) { boolean isMatching; if (componentType == NodeTypeEnum.Resource) { if (resourceType == null) { @@ -1279,12 +1232,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic { return isMatching; } - private Either, StorageOperationStatus> fetchByMainCategory(List> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { + private Either, StorageOperationStatus> fetchByMainCategory( + List> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { List components = new ArrayList<>(); - for (ImmutablePair subCategory : subcategories) { - Either, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid(subCategory.getLeft().getUniqueId(), NodeTypeEnum.Resource, - inTransaction, resourceType); + Either, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid(subCategory.getLeft().getUniqueId(), + NodeTypeEnum.Resource, inTransaction, resourceType); if (fetched.isRight()) { continue; } @@ -1299,8 +1252,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic { 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); + 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) { @@ -1324,15 +1279,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } } - public CatalogUpdateTimestamp getCatalogUpdateTime(String userId) { - - try{ + try { return toscaOperationFacade.getCatalogTimes(); - } finally { janusGraphDao.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 index 2c824c8e23..acd19e4bee 100644 --- 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 @@ -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. @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.lock.LockingTransactional; import org.openecomp.sdc.be.components.validation.AccessValidations; @@ -34,10 +36,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Created by yavivi on 04/02/2018. */ @@ -45,20 +43,21 @@ import java.util.Map; public class ExternalRefsBusinessLogic { private static final Logger log = Logger.getLogger(ExternalRefsBusinessLogic.class); - private final ExternalReferencesOperation externalReferencesOperation; private final ToscaOperationFacade toscaOperationFacade; private final AccessValidations accessValidations; private final ComponentLocker componentLocker; - public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, AccessValidations accessValidations, ComponentLocker componentLocker) { + public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, + AccessValidations accessValidations, ComponentLocker componentLocker) { this.externalReferencesOperation = externalReferencesOperation; this.toscaOperationFacade = toscaOperationFacade; this.accessValidations = accessValidations; this.componentLocker = componentLocker; } - public Either, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName, String objectType){ + 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); @@ -67,16 +66,15 @@ public class ExternalRefsBusinessLogic { return this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), componentInstanceName, objectType); } - public Either>, ActionStatus> getExternalReferences(String assetUuid, String version, String 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()){ + 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()); @@ -84,36 +82,38 @@ public class ExternalRefsBusinessLogic { } @LockingTransactional - public Either addExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, ExternalRefDTO ref) { + public Either addExternalReference(String componentId, ComponentTypeEnum componentType, String userId, + String componentInstanceName, String objectType, ExternalRefDTO ref) { return this.doAction(componentId, componentType, userId, "POST", componentId, componentInstanceName, objectType, ref.getReferenceUUID(), ""); } @LockingTransactional - public Either deleteExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, String reference) { + public Either deleteExternalReference(String componentId, ComponentTypeEnum componentType, String userId, + String componentInstanceName, String objectType, String reference) { return this.doAction(componentId, componentType, userId, "DELETE", componentId, componentInstanceName, objectType, reference, ""); } @LockingTransactional - public Either updateExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) { + public Either updateExternalReference(String componentId, ComponentTypeEnum componentType, String userId, + String componentInstanceName, String objectType, String oldRefValue, + String newRefValue) { return this.doAction(componentId, componentType, userId, "PUT", componentId, componentInstanceName, objectType, oldRefValue, newRefValue); } - public String fetchComponentUniqueIdByUuid(String uuid, ComponentTypeEnum componentType){ - Either latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch(componentType)); - if (latestServiceByUuid == null || latestServiceByUuid.isRight()){ + public String fetchComponentUniqueIdByUuid(String uuid, ComponentTypeEnum componentType) { + Either latestServiceByUuid = toscaOperationFacade + .getLatestComponentByUuid(uuid, createPropsToMatch(componentType)); + if (latestServiceByUuid == null || latestServiceByUuid.isRight()) { throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, uuid); } - //Get Component Unique ID Component component = latestServiceByUuid.left().value(); return component.getUniqueId(); } - - public Either doAction(String componentId, ComponentTypeEnum componentType, String userId, String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){ - + public Either doAction(String componentId, ComponentTypeEnum componentType, String userId, String action, String uuid, + String componentInstanceName, String objectType, String ref1, String ref2) { accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, action + " EXTERNAL REF"); - switch (action) { case "POST": return this.externalReferencesOperation.addExternalReferenceWithCommit(componentId, componentInstanceName, objectType, ref1); @@ -124,7 +124,6 @@ public class ExternalRefsBusinessLogic { default: return Either.right(ActionStatus.GENERAL_ERROR); } - } private Map createPropsToMatch(ComponentTypeEnum componentType) { @@ -132,5 +131,4 @@ public class ExternalRefsBusinessLogic { propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); return propertiesToMatch; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java index 4f092c6bd9..1f9aad5c25 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import com.google.gson.Gson; @@ -27,6 +26,8 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; +import java.io.IOException; +import java.lang.reflect.Type; import org.onap.sdc.gab.GABService; import org.onap.sdc.gab.GABServiceImpl; import org.onap.sdc.gab.model.GABQuery; @@ -41,24 +42,18 @@ import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.springframework.beans.factory.annotation.Autowired; -import java.io.IOException; -import java.lang.reflect.Type; - @org.springframework.stereotype.Component public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic { private GABService gabService; @Autowired - public GenericArtifactBrowserBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public GenericArtifactBrowserBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); gabService = new GABServiceImpl(); } @@ -67,17 +62,15 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic { return createGsonForGABResult().toJson(gabResults); } - private Gson createGsonForGABResult(){ - return new GsonBuilder().setPrettyPrinting() - .registerTypeAdapter(GABResult.class, new GABResultSerializer()) - .registerTypeAdapter(GABResults.class, new GABResultsSerializer()) - .create(); + private Gson createGsonForGABResult() { + return new GsonBuilder().setPrettyPrinting().registerTypeAdapter(GABResult.class, new GABResultSerializer()) + .registerTypeAdapter(GABResults.class, new GABResultsSerializer()).create(); } private class GABResultsSerializer implements JsonSerializer { + @Override - public JsonElement serialize(GABResults gabResults, Type type, - JsonSerializationContext jsonSerializationContext) { + public JsonElement serialize(GABResults gabResults, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject result = new JsonObject(); JsonArray jsonArray = new JsonArray(); gabResults.getRows().stream().map(jsonSerializationContext::serialize).forEach(jsonArray::add); @@ -87,6 +80,7 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic { } private class GABResultSerializer implements JsonSerializer { + @Override public JsonElement serialize(GABResult gabResult, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject result = new JsonObject(); @@ -94,5 +88,4 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic { return result; } } - } 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 fe9d44837b..fee80c65c1 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 @@ -19,10 +19,26 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; +import static java.util.stream.Collectors.toList; +import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups; +import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups; + import fj.data.Either; +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 org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FilenameUtils; @@ -89,68 +105,47 @@ 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.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 static java.util.stream.Collectors.toList; -import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups; -import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups; - @org.springframework.stereotype.Component("groupBusinessLogic") public class GroupBusinessLogic extends BaseBusinessLogic { public static final String GROUP_DELIMITER_REGEX = "\\.\\."; - public static final String INITIAL_VERSION = "0.0"; - private static final String ADDING_GROUP = "AddingGroup"; - 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 = "DeleteGroup"; - private static final Logger log = Logger.getLogger(GroupBusinessLogic.class); - private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(GroupBusinessLogic.class.getName()); - private final AccessValidations accessValidations; private final PolicyTargetsUpdateHandler policyTargetsUpdateHandler; - @javax.annotation.Resource private final GroupsOperation groupsOperation; - @Autowired - public GroupBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, AccessValidations accessValidations, - GroupsOperation groupsOperation, PolicyTargetsUpdateHandler policyTargetsUpdateHandler, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public GroupBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, AccessValidations accessValidations, + GroupsOperation groupsOperation, PolicyTargetsUpdateHandler policyTargetsUpdateHandler, + ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.accessValidations = accessValidations; this.groupsOperation = groupsOperation; this.policyTargetsUpdateHandler = policyTargetsUpdateHandler; } + 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)) || p.getInvariantName().equalsIgnoreCase(groupDefinitionName)) + .findFirst().orElse(null) != null; + } + return found; + } + private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) { String componentTypeForResponse = "SERVICE"; if (component instanceof Resource) { @@ -167,26 +162,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @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); + 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(ArtifactDefinition::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); + 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); - } /** @@ -197,43 +189,38 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param memberToscaTypes * @return */ - private Either verifyComponentInstancesAreValidMembers(Component component, String groupName, Map groupMembers, List memberToscaTypes) { - + 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(ComponentInstance::getUniqueId, p -> p)); - + Map compInstUidToCompInstMap = componentInstances.stream() + .collect(Collectors.toMap(ComponentInstance::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)); + 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 * @@ -244,8 +231,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) { - + public Either validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, + GroupDefinition updatedGroup, boolean inTransaction, + boolean shouldLock) { Either result = null; boolean failed = false; try { @@ -257,35 +245,40 @@ public class GroupBusinessLogic extends BaseBusinessLogic { validateCanWorkOnComponent(component, user.getUserId()); 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())); + 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(); + 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())); + 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 ){ + if (shouldLock) { lockComponent(componentId, component, "Update GroupDefinition Metadata"); } // 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()); + 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; - - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { if (!failed) { janusGraphDao.commit(); } else { @@ -297,10 +290,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - private Either updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) { + 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()); } @@ -338,14 +331,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic { 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); } @@ -360,7 +351,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { String nameUpdated = groupUpdate.getName(); String nameCurrent = currentGroup.getName(); if (!nameCurrent.equals(nameUpdated)) { - Either validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true); + Either validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName(), true); if (validatNameResponse.isRight()) { ResponseFormat errorRespons = validatNameResponse.right().value(); return Either.right(errorRespons); @@ -371,44 +362,41 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } /** - * 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. + * 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) { + 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 (!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); @@ -416,7 +404,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - /** * associate artifacts to a given group * @@ -426,59 +413,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) { - + public Either getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, + String userId, boolean inTransaction) { Either result = null; - // Validate user exist validateUserExists(userId); // Validate component exist org.openecomp.sdc.be.model.Component component = null; - try { ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); componentParametersView.setIgnoreUsers(false); - component = validateComponentExists(componentId, componentType, componentParametersView); - Either groupEither = findGroupOnComponent(component, groupId); - if (groupEither.isRight()) { log.debug("Failed to find group {} under component {}", groupId, component.getUniqueId()); - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); + 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)); + result = Either.right( + componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); return result; } GroupDefinition group = groupEither.left().value(); - List props = group.convertToGroupProperties(); Boolean isBase = isBaseProp(component, props); - 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(ArtifactDataDefinition::getUniqueId, a -> a)); + deploymentArtifacts = component.getDeploymentArtifacts().values().stream() + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, a -> a)); } - if (artifactsIds != null && !artifactsIds.isEmpty()) { for (String id : artifactsIds) { if (deploymentArtifacts == null || !deploymentArtifacts.containsKey(id)) { log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); result = Either.right(responseFormat); return result; } artifactsFromComponent.add(deploymentArtifacts.get(id)); } addArtifactsToList(artifacts, artifactsFromComponent); - } GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); resultInfo.setIsBase(isBase); @@ -486,17 +468,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { resultInfo.setArtifacts(artifacts); } result = Either.left(resultInfo); - return result; - } finally { closeTransaction(inTransaction, result); } - } private void addArtifactsToList(List artifacts, List artifactsFromComponent) { - artifactsFromComponent.forEach(a-> artifacts.add(new ArtifactDefinitionInfo(a))); + artifactsFromComponent.forEach(a -> artifacts.add(new ArtifactDefinitionInfo(a))); } private Boolean isBaseProp(Component component, List props) { @@ -506,16 +485,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic { 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); + BeEcompErrorManager.getInstance() + .logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); } } return isBase; } 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(); @@ -529,11 +507,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } - public Either validateGenerateVfModuleGroupNames(List allGroups, String resourceSystemName, int startGroupCounter) { + public Either validateGenerateVfModuleGroupNames(List allGroups, String resourceSystemName, + int startGroupCounter) { Either validateGenerateGroupNamesRes = Either.left(true); Collections.sort(allGroups, ArtifactTemplateInfo::compareByGroupName); for (ArtifactTemplateInfo group : allGroups) { - Either validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++); + Either validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, + group.getDescription(), startGroupCounter++); if (validateGenerateGroupNameRes.isRight()) { validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); break; @@ -555,7 +535,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { 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)); + 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)); } @@ -563,7 +544,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } Either, ResponseFormat> validateUpdateVfGroupNames(Map groups, String resourceSystemName) { - Map updatedNamesGroups = new HashMap<>(); Either, ResponseFormat> result = Either.left(updatedNamesGroups); for (Entry groupEntry : groups.entrySet()) { @@ -573,8 +553,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { 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 (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(); @@ -585,7 +565,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter); if (newGroupNameRes.isRight()) { log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); - loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(),StatusCode.ERROR.name(),"Failed to generate new vf module group name. Status is: "+newGroupNameRes.right().value()); + loggerSupportability.log(LogLevel.INFO, LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(), StatusCode.ERROR.name(), + "Failed to generate new vf module group name. Status is: " + newGroupNameRes.right().value()); result = Either.right(newGroupNameRes.right().value()); break; } @@ -608,8 +589,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { 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()); + 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(Integer::compare).get() + 1; } return counter; @@ -617,14 +600,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { public Either, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List groups, Component component) { List updatedGroups = new ArrayList<>(); - 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()) { + 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()) { @@ -633,54 +616,45 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } newGroupName = newGroupNameRes.left().value(); group.setName(newGroupName); - } updatedGroups.add(group); - } - return Either.left(updatedGroups); } - - public Either getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) { + public Either getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, + String componentInstanceId, String groupInstId, String userId, + boolean inTransaction) { Either result = null; - // Validate user exist validateUserExists(userId); // Validate component exist org.openecomp.sdc.be.model.Component component; - try { ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); componentParametersView.setIgnoreArtifacts(false); - component = validateComponentExists(componentId, componentType, componentParametersView); - Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); - + 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())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value())); result = Either.right(responseFormat); return result; } - GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); - Boolean isBase = isBaseProperty(component, group); - List artifacts = new ArrayList<>(); List artifactsIds = group.getArtifacts(); if (artifactsIds != null && !artifactsIds.isEmpty()) { - List instances = component.getComponentInstances(); if (instances != null) { - instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)) - .findFirst() - .ifPresent(f->getFirstComponentInstance(group, artifacts, artifactsIds, f)); + instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst() + .ifPresent(f -> getFirstComponentInstance(group, artifacts, artifactsIds, f)); } } GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); @@ -689,31 +663,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic { resultInfo.setArtifacts(artifacts); } result = Either.left(resultInfo); - return result; - } finally { closeTransaction(inTransaction, result); } } - private void getFirstComponentInstance(GroupInstance group, List artifacts, List artifactsIds, ComponentInstance ci) { + private void getFirstComponentInstance(GroupInstance group, List artifacts, List artifactsIds, + ComponentInstance ci) { Map deploymentArtifacts = ci.getDeploymentArtifacts(); - artifactsIds.forEach(id -> deploymentArtifacts.values().stream() - .filter(a -> a.getUniqueId().equals(id)) - .findFirst() - .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g)))); - + artifactsIds.forEach(id -> deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst() + .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g)))); List instArtifactsIds = group.getGroupInstanceArtifacts(); - instArtifactsIds.forEach(id -> deploymentArtifacts.values() - .stream() - .filter(a -> a.getUniqueId().equals(id)) - .findFirst() - .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g)))); - } + instArtifactsIds.forEach(id -> deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst() + .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g)))); + } private Boolean isBaseProperty(Component component, GroupInstance group) { - Boolean isBase = null; List props = group.convertToGroupInstancesProperties(); if (props != null && !props.isEmpty()) { @@ -721,9 +687,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { 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); + BeEcompErrorManager.getInstance() + .logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); } } return isBase; @@ -733,20 +699,21 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (!inTransaction) { if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); - janusGraphDao.rollback(); + janusGraphDao.rollback(); } else { log.debug("Going to execute commit on create group."); - janusGraphDao.commit(); + janusGraphDao.commit(); } } } - private Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) { - + 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(); + 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()) { @@ -760,39 +727,44 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } - private Boolean validateMinMaxAndInitialCountPropertyLogic(Map newValues, Map currValues, Map parentValues) { - + private Boolean validateMinMaxAndInitialCountPropertyLogic(Map newValues, Map currValues, + Map parentValues) { for (Entry entry : newValues.entrySet()) { PropertyNames currPropertyName = entry.getKey(); if (currPropertyName == PropertyNames.MIN_INSTANCES) { String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); String maxValue = getMaxValue(newValues, currValues); - validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); + validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), + new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); } 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); - validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); + 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); + validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), + new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); } else if (currPropertyName == PropertyNames.MAX_INSTANCES) { String minValue = getMinValue(newValues, currValues); String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); - validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); + validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), + new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue)); } } return true; } private String getMaxValue(Map newValues, Map currValues) { - return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) + : currValues.get(PropertyNames.INITIAL_COUNT); } private String getMinValue(Map newValues, Map currValues) { - return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) + : currValues.get(PropertyNames.INITIAL_COUNT); } - private Boolean validateValueInRange(ImmutablePair newValue, ImmutablePair min, ImmutablePair max) { + private Boolean validateValueInRange(ImmutablePair newValue, ImmutablePair min, + ImmutablePair max) { 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()); @@ -801,8 +773,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY); } else if (newValueInt < minInt || newValueInt > maxInt) { log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); - throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), - maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, + newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue()); } return true; } @@ -826,17 +798,20 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param newProperties * @return */ - public Either validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List newProperties) { - + public Either validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, + GroupInstance oldGroupInstance, + List newProperties) { Either actionResult = null; Either updateGroupInstanceResult = null; List validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); if (actionResult == null) { List validatedReducedNewProperties = validateRes; - updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); + 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()))); + actionResult = Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); } } if (actionResult == null) { @@ -845,11 +820,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return actionResult; } - private List validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List newProperties) { - + private List validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, + List newProperties) { Boolean validationRes = null; List actionResult = null; - Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); + Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream() + .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); Map newPropertyValues = new EnumMap<>(PropertyNames.class); List reducedProperties = new ArrayList<>(); String currPropertyName; @@ -874,7 +850,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return actionResult; } - private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, Map propertyValues, Map parentPropertyValues) { + private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, + Map propertyValues, + Map parentPropertyValues) { PropertyNames[] allPropertyNames = PropertyNames.values(); for (PropertyNames name : allPropertyNames) { if (isUpdatable(name)) { @@ -884,8 +862,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - private Boolean handleAndAddProperty(List reducedProperties, Map newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { - + private Boolean handleAndAddProperty(List reducedProperties, Map newPropertyValues, + GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { Boolean validationRes = null; String currPropertyName = currNewProperty.getName(); PropertyNames propertyName = PropertyNames.findName(currPropertyName); @@ -908,11 +886,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private boolean isUpdatable(PropertyNames updatablePropertyName) { - return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); + 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) { - + 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()); @@ -932,7 +913,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private int convertIfUnboundMax(String value) { - int result; if (!NumberUtils.isNumber(value)) { result = Integer.MAX_VALUE; @@ -943,9 +923,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private Boolean validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - String parentValue = existingProperty.getParentValue(); - newProperty.setParentValue(parentValue); if (StringUtils.isEmpty(newProperty.getValue())) { newProperty.setValue(parentValue); @@ -955,34 +933,30 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } 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); + log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), + status); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status)); } return true; } 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()); + 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()); } } @LockingTransactional - public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType, - String userId) { - + public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType, String userId) { Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, CREATE_GROUP); - validateGroupTypePerComponent(groupType, component); - - GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false) - .left() - .on(se -> onGroupTypeNotFound(component)); - + GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false).left() + .on(se -> onGroupTypeNotFound(component)); boolean hasExistingGroups = CollectionUtils.isNotEmpty(component.getGroups()); GroupDefinition groupDefinition = new GroupDefinition(); groupDefinition.setType(groupType); - //find next valid counter int nextCounter = 0; if (hasExistingGroups) { @@ -993,26 +967,17 @@ public class GroupBusinessLogic extends BaseBusinessLogic { groupDefinition.setDescription(groupTypeDefinition.getDescription()); groupDefinition.setInvariantName(name); groupDefinition.setCreatedFrom(CreatedFrom.UI); - //Add default type properties List groupTypeProperties = groupTypeDefinition.getProperties(); - List properties = groupTypeProperties.stream() - .map(GroupProperty::new) - .collect(toList()); + List properties = groupTypeProperties.stream().map(GroupProperty::new).collect(toList()); groupDefinition.convertFromGroupProperties(properties); - groupDefinition.convertCapabilityDefinitions(groupTypeDefinition.getCapabilities()); - List gdList; if (toscaOperationFacade.canAddGroups(componentId)) { - gdList = addGroups(component, Arrays.asList(groupDefinition), false) - .left() - .on(this::onFailedGroupDBOperation); + gdList = addGroups(component, Arrays.asList(groupDefinition), false).left().on(this::onFailedGroupDBOperation); } else { //createGroups also creates an edge and vertex to store group data - gdList = createGroups(component, Arrays.asList(groupDefinition), false) - .left() - .on(this::onFailedGroupDBOperation); + gdList = createGroups(component, Arrays.asList(groupDefinition), false).left().on(this::onFailedGroupDBOperation); } return gdList.get(0); } @@ -1020,51 +985,35 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private void validateGroupTypePerComponent(String groupType, Component component) { String specificType = component.getComponentMetadataDefinition().getMetadataDataDefinition().getActualComponentType(); if (!component.isTopologyTemplate()) { - throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, - specificType); + throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType); } Map> excludedGroupTypesMap = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludedGroupTypesMapping(); - + .getExcludedGroupTypesMapping(); if (MapUtils.isNotEmpty(excludedGroupTypesMap) && StringUtils.isNotEmpty(specificType)) { Set excludedGroupTypesPerComponent = excludedGroupTypesMap.get(specificType); - if (excludedGroupTypesPerComponent!=null && excludedGroupTypesPerComponent.contains(groupType)) { + if (excludedGroupTypesPerComponent != null && excludedGroupTypesPerComponent.contains(groupType)) { throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType); } } } private int getNewGroupCounter(Component component) { - List existingNames = component.getGroups() - .stream() - .map(GroupDataDefinition::getInvariantName) - .collect(toList()); - List existingIds = component.getGroups() - .stream() - .map(GroupDataDefinition::getUniqueId) - .collect(toList()); + List existingNames = component.getGroups().stream().map(GroupDataDefinition::getInvariantName).collect(toList()); + List existingIds = component.getGroups().stream().map(GroupDataDefinition::getUniqueId).collect(toList()); existingIds.addAll(existingNames); - return Utils.getNextCounter(existingIds); } @LockingTransactional - public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId, - String userId, GroupDefinition updatedGroup) { + public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId, String userId, + GroupDefinition updatedGroup) { Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, UPDATE_GROUP); - - GroupDefinition existingGroup = findGroupOnComponent(component, groupId) - .left() - .on(se -> onGroupNotFoundInComponentError(component, groupId)); - + 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); + return updateGroup(component, existingGroup, existingGroupName).left().on(this::onFailedUpdateGroupDBOperation); } private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) { @@ -1080,18 +1029,11 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } @LockingTransactional - public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId, - String userId) { + public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId, String userId) { Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, 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); - + GroupDefinition groupDefinition = findGroupOnComponent(component, groupId).left() + .on(se -> onGroupNotFoundInComponentError(component, groupId)); + List gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition)).left().on(this::onFailedGroupDBOperation); updatePolicyTargetReferencingDeletedGroup(groupId, component); return gdList.get(0); } @@ -1107,17 +1049,18 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private GroupDefinition onGroupNotFoundInComponentError(Component component, String groupId) { - throw new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, groupId, - component.getSystemName(), getComponentTypeForResponse(component)); + throw new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), + getComponentTypeForResponse(component)); } private GroupTypeDefinition onGroupTypeNotFound(Component component) { throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, component.getSystemName(), - component.getComponentType().toString()); + component.getComponentType().toString()); } private void updatePolicyTargetReferencingDeletedGroup(String groupId, Component component) { - log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}", component.getUniqueId(), groupId); + log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}", + component.getUniqueId(), groupId); ActionStatus actionStatus = policyTargetsUpdateHandler.removePoliciesTargets(component, groupId, PolicyTargetType.GROUPS); if (ActionStatus.OK != actionStatus) { janusGraphDao.rollback(); @@ -1125,20 +1068,19 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - - public Either, ResponseFormat> createGroups(Component component, final List groupDefinitions, boolean fromCsar) { - + public Either, ResponseFormat> createGroups(Component component, final List groupDefinitions, + boolean fromCsar) { Map groups = new HashMap<>(); Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { JanusGraphOperationStatus 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.convertJanusGraphStatusToStorageStatus(status)))); - + BeEcompErrorManager.getInstance() + .logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } - // handle groups and convert to tosca data if (groupDefinitions != null && !groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { @@ -1149,13 +1091,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } GroupDefinition handledGroup = handleGroupRes.left().value(); groups.put(handledGroup.getInvariantName(), new GroupDataDefinition(handledGroup)); - } } if (result == null) { createGroupsResult = groupsOperation.createGroups(component, groups); if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + result = Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } } if (result == null) { @@ -1168,26 +1110,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } - private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List groupDefinitions, boolean fromCsar) { + private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List groupDefinitions, + boolean fromCsar) { groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields); - StorageOperationStatus status = groupsOperation.updateCalculatedCapabilitiesWithProperties(component.getUniqueId(), - extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar)); - if(status != StorageOperationStatus.OK){ - log.error("#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ", component.getUniqueId()); + StorageOperationStatus status = groupsOperation + .updateCalculatedCapabilitiesWithProperties(component.getUniqueId(), extractCapabilitiesFromGroups(groupDefinitions), + extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar)); + if (status != StorageOperationStatus.OK) { + log.error( + "#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ", + component.getUniqueId()); rollbackWithException(componentsUtils.convertFromStorageResponse(status)); } } - private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component, - final List groupDefinitions, boolean fromCsar) { - final List nonNullGroupDefinitions = - (groupDefinitions == null) ? Collections.emptyList() : groupDefinitions; - + private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component, final List groupDefinitions, + boolean fromCsar) { + final List nonNullGroupDefinitions = (groupDefinitions == null) ? Collections.emptyList() : groupDefinitions; nonNullGroupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields); - StorageOperationStatus status = groupsOperation.addCalculatedCapabilitiesWithProperties( - component.getUniqueId(), - extractCapabilitiesFromGroups(nonNullGroupDefinitions), - extractCapabilityPropertiesFromGroups(nonNullGroupDefinitions, fromCsar)); + StorageOperationStatus status = groupsOperation + .addCalculatedCapabilitiesWithProperties(component.getUniqueId(), extractCapabilitiesFromGroups(nonNullGroupDefinitions), + extractCapabilityPropertiesFromGroups(nonNullGroupDefinitions, fromCsar)); if (status != StorageOperationStatus.OK) { log.error( "#addCalculatedCapabilitiesWithPropertiesToComponent - failed to add the groups' calculated capabilities with the properties to the component {}. ", @@ -1198,26 +1141,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private void deleteCalculatedCapabilitiesWithPropertiesFromComponent(Component component, final List groupDefinitions) { StorageOperationStatus status = groupsOperation.deleteCalculatedCapabilitiesWithProperties(component.getUniqueId(), groupDefinitions); - if(status != StorageOperationStatus.OK){ - log.error("#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ", component.getUniqueId()); + if (status != StorageOperationStatus.OK) { + log.error( + "#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ", + component.getUniqueId()); rollbackWithException(componentsUtils.convertFromStorageResponse(status)); } } - public Either, ResponseFormat> addGroups(Component component, final List groupDefinitions, boolean fromCsar) { - + public Either, ResponseFormat> addGroups(Component component, final List groupDefinitions, + boolean fromCsar) { Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; List groups = new ArrayList<>(); - Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { JanusGraphOperationStatus 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.convertJanusGraphStatusToStorageStatus(status)))); - + BeEcompErrorManager.getInstance() + .logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } - // handle groups and convert to tosca data if (groupDefinitions != null && !groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { @@ -1233,7 +1177,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (result == null) { createGroupsResult = groupsOperation.addGroups(component, groups); if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + result = Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } component.addGroups(createGroupsResult.left().value()); } @@ -1247,16 +1192,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } public Either, ResponseFormat> deleteGroups(Component component, List groupDefinitions) { - Either, StorageOperationStatus> deleteGroupsResult; - deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList())); if (deleteGroupsResult.isRight()) { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value()))); } else { deleteCalculatedCapabilitiesWithPropertiesFromComponent(component, groupDefinitions); } - if (component.getGroups()!=null) { + if (component.getGroups() != null) { component.getGroups().removeAll(deleteGroupsResult.left().value()); } return Either.left(deleteGroupsResult.left().value()); @@ -1264,15 +1207,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { /** * Update specific group version - * @param fromCsar TODO * + * @param fromCsar TODO */ public Either, ResponseFormat> updateGroups(Component component, List groupDefinitions, boolean fromCsar) { - Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult; - - createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR); + createGroupsResult = groupsOperation + .updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR); if (createGroupsResult.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } @@ -1285,15 +1227,17 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } - private Either handleGroup(Component component, GroupDefinition groupDefinition, Map allDAtaTypes) { - + private Either handleGroup(Component component, GroupDefinition groupDefinition, + Map allDAtaTypes) { log.trace("Going to create group {}", groupDefinition); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),StatusCode.STARTED,"Start to create group: {}",groupDefinition.getName()+ " for component " + component.getName()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Start to create group: {}", groupDefinition.getName() + " for component " + component.getName()); // 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)); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse)); } // 4. verify type of group exist String groupType = groupDefinition.getType(); @@ -1304,56 +1248,60 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (getGroupType.isRight()) { StorageOperationStatus status = getGroupType.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { - loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} cannot be found",groupDefinition.getName()); - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "group {} cannot be found", groupDefinition.getName()); + 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()); - + 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); + 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); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} does not have properties ",groupDefinition.getName()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND)))); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "group {} does not have properties ", groupDefinition.getName()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND)))); } - - Map groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p)); - + Map groupTypePropertiesMap = groupTypeProperties.stream() + .collect(Collectors.toMap(PropertyDefinition::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.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value())))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils + .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value())))); } updatedGroupTypeProperties.add(addPropertyResult.left().value()); - i++; } } - if (groupDefinition.getUniqueId() == null) { String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName); groupDefinition.setUniqueId(uid); @@ -1363,42 +1311,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic { groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); groupDefinition.setVersion(INITIAL_VERSION); groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"group {} has been created ",groupDefinition.getName()); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "group {} has been created ", groupDefinition.getName()); 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)) - || p.getInvariantName().equalsIgnoreCase(groupDefinitionName)) - .findFirst().orElse(null) != null; - } - return found; - } - - private Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map allDataTypes, String groupType) { - + private Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, + Map allDataTypes, String groupType) { if (prop == null) { return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT); } - String propertyType = prop.getType(); String value = groupProperty.getValue(); - Either checkInnerType = propertyOperation.checkInnerType(prop); if (checkInnerType.isRight()) { JanusGraphOperationStatus 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(); @@ -1411,10 +1344,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic { newValue = object.toString(); } } - - String uniqueId = shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index) - : prop.getUniqueId(); - + String uniqueId = + shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index) : prop.getUniqueId(); groupProperty.setUniqueId(uniqueId); groupProperty.setValue(newValue); groupProperty.setType(prop.getType()); @@ -1423,16 +1354,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic { 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/GroupBusinessLogicNew.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java index eb576a46f6..46b6f79133 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java @@ -21,6 +21,14 @@ */ package org.openecomp.sdc.be.components.impl; +import static org.openecomp.sdc.be.components.impl.BaseBusinessLogic.enumHasValueFilter; + +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 org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -46,15 +54,6 @@ import org.openecomp.sdc.be.model.operations.impl.GroupOperation; import org.openecomp.sdc.common.util.ValidationUtils; import org.springframework.transaction.annotation.Transactional; -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 static org.openecomp.sdc.be.components.impl.BaseBusinessLogic.enumHasValueFilter; - @org.springframework.stereotype.Component public class GroupBusinessLogicNew { @@ -63,7 +62,8 @@ public class GroupBusinessLogicNew { private final GroupsOperation groupsOperation; private final GroupOperation groupOperation; - public GroupBusinessLogicNew(AccessValidations accessValidations, ComponentValidations componentValidations, GroupsOperation groupsOperation, GroupOperation groupOperation) { + public GroupBusinessLogicNew(AccessValidations accessValidations, ComponentValidations componentValidations, GroupsOperation groupsOperation, + GroupOperation groupOperation) { this.accessValidations = accessValidations; this.componentValidations = componentValidations; this.groupsOperation = groupsOperation; @@ -71,7 +71,8 @@ public class GroupBusinessLogicNew { } @LockingTransactional - public List updateMembers(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, List members) { + public List updateMembers(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, + List members) { Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP MEMBERS"); GroupDefinition groupDefinition = getGroup(component, groupUniqueId); groupDefinition.setMembers(buildMembersMap(component, members)); @@ -80,13 +81,13 @@ public class GroupBusinessLogicNew { } @LockingTransactional - public List updateProperties(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, List newProperties) { + public List updateProperties(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, + List newProperties) { Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP PROPERTIES"); GroupDefinition currentGroup = getGroup(component, groupUniqueId); validateUpdatedPropertiesAndSetEmptyValues(currentGroup, newProperties); - return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties, PromoteVersionEnum.MINOR) - .left() - .on(this::onUpdatePropertyError); + return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties, PromoteVersionEnum.MINOR).left() + .on(this::onUpdatePropertyError); } @Transactional @@ -110,31 +111,26 @@ public class GroupBusinessLogicNew { } private ComponentInstance getComponentInstance(Component component, String memberUniqueId) { - return componentValidations.getComponentInstance(component, memberUniqueId) - .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, - memberUniqueId, "", - component.getActualComponentType(), component.getSystemName())); + return componentValidations.getComponentInstance(component, memberUniqueId).orElseThrow( + () -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, memberUniqueId, "", + component.getActualComponentType(), component.getSystemName())); } private GroupDefinition getGroup(Component component, String groupUniqueId) { - return component.getGroupById(groupUniqueId) - .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, - component.getSystemName(), component.getActualComponentType())); + return component.getGroupById(groupUniqueId).orElseThrow( + () -> new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, component.getSystemName(), component.getActualComponentType())); } private void validateUpdatedPropertiesAndSetEmptyValues(GroupDefinition originalGroup, List groupPropertiesToUpdate) { - if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) { throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY); } if (CollectionUtils.isEmpty(originalGroup.getProperties())) { - throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName()); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, + groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName()); } - Map originalProperties = originalGroup.convertToGroupProperties() - .stream() - .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); - - + Map originalProperties = originalGroup.convertToGroupProperties().stream() + .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); for (GroupProperty gp : groupPropertiesToUpdate) { String updatedPropertyName = gp.getName(); if (!originalProperties.containsKey(updatedPropertyName)) { @@ -151,12 +147,10 @@ public class GroupBusinessLogicNew { throw new StorageException(sos, updatedPropertyName); } } - validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup); } private void validatePropertyBusinessLogic(List groupPropertiesToUpdate, GroupDefinition originalGroup) { - Map enumValueMap = new EnumMap<>(PropertyDefinition.PropertyNames.class); for (GroupProperty gp : groupPropertiesToUpdate) { // Filter out non special properties which does not have Enum @@ -168,20 +162,19 @@ public class GroupBusinessLogicNew { if (MapUtils.isEmpty(enumValueMap)) { return; } - validateVFInstancesLogic(enumValueMap, prepareMapWithOriginalProperties(originalGroup)); - - if (enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION) || enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) { - groupPropertiesToUpdate.stream() - .filter(e -> enumHasValueFilter(e.getName(), PropertyDefinition.PropertyNames::findName, PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION, PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) - .forEach(this::validateFreeText); + if (enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION) || enumValueMap + .containsKey(PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) { + groupPropertiesToUpdate.stream().filter(e -> enumHasValueFilter(e.getName(), PropertyDefinition.PropertyNames::findName, + PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION, PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) + .forEach(this::validateFreeText); } } private Map prepareMapWithOriginalProperties(GroupDefinition originalGroup) { Map oldValueMap = new EnumMap<>(PropertyDefinition.PropertyNames.class); - PropertyDefinition.PropertyNames[] propertiesToCheck = new PropertyDefinition.PropertyNames[] { PropertyDefinition.PropertyNames.INITIAL_COUNT, PropertyDefinition.PropertyNames.MAX_INSTANCES, PropertyDefinition.PropertyNames.MIN_INSTANCES }; - + PropertyDefinition.PropertyNames[] propertiesToCheck = new PropertyDefinition.PropertyNames[]{PropertyDefinition.PropertyNames.INITIAL_COUNT, + PropertyDefinition.PropertyNames.MAX_INSTANCES, PropertyDefinition.PropertyNames.MIN_INSTANCES}; for (GroupProperty gp : originalGroup.convertToGroupProperties()) { if (enumHasValueFilter(gp.getName(), PropertyDefinition.PropertyNames::findName, propertiesToCheck)) { oldValueMap.put(PropertyDefinition.PropertyNames.findName(gp.getName()), gp.getValue()); @@ -193,35 +186,39 @@ public class GroupBusinessLogicNew { return oldValueMap; } - private void validateVFInstancesLogic(Map newValues, Map parentValues) { - if (!newValues.containsKey(PropertyDefinition.PropertyNames.INITIAL_COUNT) - && !newValues.containsKey(PropertyDefinition.PropertyNames.MAX_INSTANCES) - && !newValues.containsKey(PropertyDefinition.PropertyNames.MIN_INSTANCES)) { + private void validateVFInstancesLogic(Map newValues, + Map parentValues) { + if (!newValues.containsKey(PropertyDefinition.PropertyNames.INITIAL_COUNT) && !newValues + .containsKey(PropertyDefinition.PropertyNames.MAX_INSTANCES) && !newValues.containsKey(PropertyDefinition.PropertyNames.MIN_INSTANCES)) { return; } int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES); int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT); int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES); - - if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT) - && (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances)) { - throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyDefinition.PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances)); + if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT) && (latestInitialCount > latestMaxInstances + || latestInitialCount < latestMinInstances)) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, + PropertyDefinition.PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), + String.valueOf(latestMaxInstances)); } - if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES) && - latestMaxInstances < latestInitialCount) { - throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyDefinition.PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount)); + if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES) && latestMaxInstances < latestInitialCount) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, + PropertyDefinition.PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount)); } - if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES) && - latestMinInstances > latestInitialCount) { - throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyDefinition.PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount)); + if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES) && latestMinInstances > latestInitialCount) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, + PropertyDefinition.PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount)); } } - private boolean isPropertyChanged(Map newValues, Map parentValues, final PropertyDefinition.PropertyNames minInstances) { + private boolean isPropertyChanged(Map newValues, + Map parentValues, + final PropertyDefinition.PropertyNames minInstances) { return newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances)); } - private int getLatestIntProperty(Map newValues, Map parentValues, PropertyDefinition.PropertyNames propertyKey) { + private int getLatestIntProperty(Map newValues, + Map parentValues, PropertyDefinition.PropertyNames propertyKey) { String value; if (newValues.containsKey(propertyKey)) { value = newValues.get(propertyKey); @@ -240,22 +237,19 @@ public class GroupBusinessLogicNew { groupProperty2Duplicate.setValue(null); groupProperty2Duplicate.setSchema(null); groupProperty2Duplicate.setParentUniqueId(null); - return StringUtils.equals(groupProperty1Duplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()) - && groupProperty1Duplicate.equals(groupProperty2Duplicate); + return StringUtils.equals(groupProperty1Duplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()) && groupProperty1Duplicate + .equals(groupProperty2Duplicate); } private void validateFreeText(GroupProperty groupPropertyToUpdate) { final String groupTypeValue = groupPropertyToUpdate.getValue(); if (!org.apache.commons.lang3.StringUtils.isEmpty(groupTypeValue)) { if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, - NodeTypeEnum.Property.getName(), - String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, NodeTypeEnum.Property.getName(), + String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); } else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION, - NodeTypeEnum.Property.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION, NodeTypeEnum.Property.getName()); } } } - } 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 index ee53c35884..4a67b09634 100644 --- 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 @@ -21,6 +21,11 @@ */ package org.openecomp.sdc.be.components.impl; +import static java.util.Collections.emptySet; + +import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.validation.UserValidations; @@ -33,12 +38,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static java.util.Collections.emptySet; - @Component("groupTypeBusinessLogic") public class GroupTypeBusinessLogic { @@ -47,14 +46,14 @@ public class GroupTypeBusinessLogic { private final UserValidations userValidations; private final ComponentsUtils componentsUtils; - public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, JanusGraphDao janusGraphDao, UserValidations userValidations, ComponentsUtils componentsUtils) { + public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, JanusGraphDao janusGraphDao, UserValidations userValidations, + ComponentsUtils componentsUtils) { this.groupTypeOperation = groupTypeOperation; this.janusGraphDao = janusGraphDao; this.userValidations = userValidations; this.componentsUtils = componentsUtils; } - public List getAllGroupTypes(String userId, String internalComponentType) { try { userValidations.validateUserExists(userId); @@ -66,16 +65,15 @@ public class GroupTypeBusinessLogic { } public GroupTypeDefinition getLatestGroupTypeByType(String groupTypeName) { - return groupTypeOperation.getLatestGroupTypeByType(groupTypeName, true) - .left() - .on(e -> failOnGetGroupType(e, groupTypeName)); + return groupTypeOperation.getLatestGroupTypeByType(groupTypeName, true).left().on(e -> failOnGetGroupType(e, groupTypeName)); } public Set getExcludedGroupTypes(String internalComponentType) { if (StringUtils.isEmpty(internalComponentType)) { return emptySet(); } - Map> excludedGroupTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping(); + Map> excludedGroupTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration() + .getExcludedGroupTypesMapping(); Set excludedTypes = excludedGroupTypesMapping.get(internalComponentType); return excludedTypes == null ? emptySet() : excludedTypes; } 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 24cbb3e3a4..d3640a71a7 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 @@ -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. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData; @@ -41,11 +44,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - @Component("groupTypeImportManager") public class GroupTypeImportManager { @@ -55,7 +53,8 @@ public class GroupTypeImportManager { private final ToscaOperationFacade toscaOperationFacade; private final CommonImportManager commonImportManager; - public GroupTypeImportManager(GroupTypeOperation groupTypeOperation, ComponentsUtils componentsUtils, ToscaOperationFacade toscaOperationFacade, CommonImportManager commonImportManager) { + public GroupTypeImportManager(GroupTypeOperation groupTypeOperation, ComponentsUtils componentsUtils, ToscaOperationFacade toscaOperationFacade, + CommonImportManager commonImportManager) { this.groupTypeOperation = groupTypeOperation; this.componentsUtils = componentsUtils; this.toscaOperationFacade = toscaOperationFacade; @@ -70,22 +69,23 @@ public class GroupTypeImportManager { return commonImportManager.createElementTypesFromYml(groupTypesYml, this::createGroupType); } - private Either>, ResponseFormat> upsertGroupTypesByDao(List groupTypesToCreate) { - return commonImportManager.createElementTypesByDao(groupTypesToCreate, this::validateGroupType, groupType -> new ImmutablePair<>(ElementTypeEnum.GROUP_TYPE, groupType.getType()), - groupTypeOperation::getLatestGroupTypeByType, groupTypeOperation::addGroupType, this::updateGroupType); + private Either>, ResponseFormat> upsertGroupTypesByDao( + List groupTypesToCreate) { + return commonImportManager.createElementTypesByDao(groupTypesToCreate, this::validateGroupType, + groupType -> new ImmutablePair<>(ElementTypeEnum.GROUP_TYPE, groupType.getType()), groupTypeOperation::getLatestGroupTypeByType, + groupTypeOperation::addGroupType, this::updateGroupType); } private Either updateGroupType(GroupTypeDefinition newGroupType, GroupTypeDefinition oldGroupType) { Either validationRes = groupTypeOperation.validateUpdateProperties(newGroupType); if (validationRes.isRight()) { - log.error("#updateGroupType - One or all properties of group type {} not valid. status is {}", newGroupType, validationRes.right().value()); + log.error("#updateGroupType - One or all properties of group type {} not valid. status is {}", newGroupType, + validationRes.right().value()); return validationRes; } - if (TypeCompareUtils.isGroupTypesEquals(newGroupType, oldGroupType)) { return TypeCompareUtils.typeAlreadyExists(); } - return groupTypeOperation.updateGroupType(newGroupType, oldGroupType); } @@ -98,7 +98,8 @@ public class GroupTypeImportManager { } else { for (String member : groupType.getMembers()) { // Verify that such Resource exist - Either eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member); + Either eitherMemberExist = toscaOperationFacade + .getLatestByToscaResourceName(member); if (eitherMemberExist.isRight()) { StorageOperationStatus operationStatus = eitherMemberExist.right().value(); log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus); @@ -108,16 +109,13 @@ public class GroupTypeImportManager { break; } } - } } return result; } private GroupTypeDefinition createGroupType(String groupTypeName, Map toscaJson) { - GroupTypeDefinition groupType = new GroupTypeDefinition(); - if (toscaJson != null) { // Description commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), groupType::setDescription); @@ -132,11 +130,8 @@ public class GroupTypeImportManager { groupType.setCapabilities(capabilities); // Members commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.MEMBERS.getElementName(), groupType::setMembers); - groupType.setType(groupTypeName); - groupType.setHighestVersion(true); - groupType.setVersion(TypeUtils.getFirstCertifiedVersionVersion()); } return groupType; @@ -148,41 +143,24 @@ public class GroupTypeImportManager { */ private Map createCapabilities(Map toscaJson) { CapabilityTypeToscaJsonHolder capabilityTypeToscaJsonHolder = new CapabilityTypeToscaJsonHolder(); - commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName(), capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson); + commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName(), + capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson); Map capabilities; if (capabilityTypeToscaJsonHolder.isEmpty()) { capabilities = Collections.emptyMap(); - } - else { - capabilities = commonImportManager.createElementTypesMapFromToscaJsonMap(this::createCapability, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson()); + } else { + capabilities = commonImportManager + .createElementTypesMapFromToscaJsonMap(this::createCapability, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson()); } return capabilities; } - - 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 CapabilityDefinition createCapability(String capabilityName, Map toscaJson) { CapabilityDefinition capability = new CapabilityDefinition(); - capability.setName(capabilityName); commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TYPE.getElementName(), capability::setType); // Properties CommonImportManager.setProperties(toscaJson, pl -> capability.setProperties(map(pl))); - return capability; } @@ -191,9 +169,23 @@ public class GroupTypeImportManager { * @return */ private List map(List pl) { - return pl.stream() - .map(ComponentInstanceProperty::new) - .collect(Collectors.toList()); + return pl.stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); } + private class CapabilityTypeToscaJsonHolder { + + private Map capabilityTypeToscaJson; + + public Map getCapabilityTypeToscaJson() { + return capabilityTypeToscaJson; + } + + public void setCapabilityTypeToscaJson(Map capabilityTypeToscaJson) { + this.capabilityTypeToscaJson = capabilityTypeToscaJson; + } + + public boolean isEmpty() { + return capabilityTypeToscaJson == 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 index ddf462639b..ccc7feb4da 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.common.api.HealthCheckInfo; 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 57e6eb54a7..ea41995683 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 @@ -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. @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; public interface IDeploymentArtifactTypeConfigGetter { + 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 ed26eade32..f53726743c 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import static org.apache.commons.collections.CollectionUtils.isEmpty; @@ -86,10 +85,8 @@ public final class ImportUtils { private static final CustomResolver customResolver = new CustomResolver(); private static final Yaml strictYamlLoader = new YamlLoader().getStrictYamlLoader(); - - private static ComponentsUtils componentsUtils; - private static final Logger log = Logger.getLogger(ImportUtils.class); + private static ComponentsUtils componentsUtils; private ImportUtils() { } @@ -99,21 +96,6 @@ public final class ImportUtils { componentsUtils = componentsUtils; } - 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(); @@ -142,56 +124,17 @@ public final class ImportUtils { 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); + 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_NON_CERTIFIED_VERSION = "0.1"; - public static final String VENDOR_NAME = "ONAP (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 static final String ESCAPED_DOUBLE_QUOTE = "\""; - public static final String QUOTE = "'"; - public static final String VF_DESCRIPTION = "Nested VF in service"; - - private Constants() { - } - } - - 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, INVALID_ATTRIBUTE_NAME - } - - public enum ToscaElementTypeEnum { - BOOLEAN, STRING, MAP, LIST, ALL - } - @SuppressWarnings("unchecked") - private static void handleElementNameNotFound(String elementName, Object elementValue, - ToscaElementTypeEnum elementType, List returnedList) { + private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, + List returnedList) { if (elementValue instanceof Map) { findToscaElements((Map) elementValue, elementName, elementType, returnedList); } else if (elementValue instanceof List) { @@ -200,9 +143,8 @@ public final class ImportUtils { } @SuppressWarnings("unchecked") - private static void addFoundElementAccordingToItsType(String elementName, ToscaElementTypeEnum elementType, - List returnedList, Object elementValue) { - + private static void addFoundElementAccordingToItsType(String elementName, ToscaElementTypeEnum elementType, List returnedList, + Object elementValue) { if (elementValue instanceof Boolean) { if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) { returnedList.add(elementValue); @@ -216,13 +158,11 @@ public final class ImportUtils { returnedList.add(elementValue); } findToscaElements((Map) elementValue, elementName, elementType, returnedList); - } else if (elementValue instanceof List) { if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) { returnedList.add(elementValue); } findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); - } // For Integer, Double etc... else if (elementType == ToscaElementTypeEnum.ALL && elementValue != null) { @@ -230,13 +170,12 @@ public final class ImportUtils { } } - private static void findAllToscaElementsInList(List list, String elementName, - ToscaElementTypeEnum elementType, List returnedList) { + private static void findAllToscaElementsInList(List list, String elementName, ToscaElementTypeEnum elementType, + List returnedList) { list.forEach(elementValue -> handleElementNameNotFound(elementName, elementValue, elementType, returnedList)); } - public static Either findToscaElement(Map toscaJson, - TypeUtils.ToscaTagNamesEnum elementName, + public static Either findToscaElement(Map toscaJson, TypeUtils.ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) { List foundElements = new ArrayList<>(); findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements); @@ -247,22 +186,19 @@ public final class ImportUtils { } /** - * 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 + * 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 * @return */ - public static Either, ResultStatusEnum> findToscaElements(Map toscaJson, - String elementName, - ToscaElementTypeEnum elementType, - List returnedList) { + 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)) { skipKey = handleFoundElement(toscaJson, elementName, elementType, returnedList); } - Iterator> keyValItr = toscaJson.entrySet().iterator(); while (keyValItr.hasNext()) { Entry keyValEntry = keyValItr.next(); @@ -270,53 +206,45 @@ public final class ImportUtils { handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList); } } - if (!isEmpty(returnedList)) { returnedElement = Either.left(returnedList); } - return returnedElement; } - private static String handleFoundElement(Map toscaJson, String elementName, - ToscaElementTypeEnum elementType, List returnedList) { + private static String handleFoundElement(Map toscaJson, String elementName, ToscaElementTypeEnum elementType, + List returnedList) { Object elementValue = toscaJson.get(elementName); addFoundElementAccordingToItsType(elementName, elementType, returnedList, elementValue); return elementName; - } @SuppressWarnings("unchecked") public static Either, ResultStatusEnum> findFirstToscaListElement(Map toscaJson, TypeUtils.ToscaTagNamesEnum toscaTagName) { Either, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, - ToscaElementTypeEnum.LIST); + 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, TypeUtils.ToscaTagNamesEnum toscaTagName) { Either, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, - ToscaElementTypeEnum.MAP); + 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, TypeUtils.ToscaTagNamesEnum toscaTagName) { Either returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, - ToscaElementTypeEnum.STRING); + Either findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING); if (findFirstToscaElements.isLeft()) { returnedElement = Either.left((String) findFirstToscaElements.left().value()); } @@ -324,8 +252,7 @@ public final class ImportUtils { } /** - * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or - * ELEMENT_NOT_FOUND status + * 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 @@ -334,8 +261,7 @@ public final class ImportUtils { public static Either findFirstToscaBooleanElement(Map toscaJson, TypeUtils.ToscaTagNamesEnum toscaTagName) { Either returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, - ToscaElementTypeEnum.BOOLEAN); + Either findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN); if (findFirstToscaElements.isLeft()) { returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value())); } @@ -349,8 +275,7 @@ public final class ImportUtils { } } - private static List getPropertyConstraints(final Map propertyValue, - final String propertyType) { + private static List getPropertyConstraints(final Map propertyValue, final String propertyType) { final List propertyFieldConstraints = findCurrentLevelConstraintsElement(propertyValue); if (CollectionUtils.isEmpty(propertyFieldConstraints)) { return Collections.emptyList(); @@ -358,12 +283,9 @@ public final class ImportUtils { final List constraintList = new ArrayList<>(); final Type constraintType = new TypeToken() { }.getType(); - final Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()) - .create(); - + final Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); for (final Object constraintJson : propertyFieldConstraints) { - final PropertyConstraint propertyConstraint = validateAndGetPropertyConstraint(propertyType, constraintType, - gson, constraintJson); + final PropertyConstraint propertyConstraint = validateAndGetPropertyConstraint(propertyType, constraintType, gson, constraintJson); constraintList.add(propertyConstraint); } return constraintList; @@ -380,26 +302,22 @@ public final class ImportUtils { } } return constraints; - } - private static PropertyConstraint validateAndGetPropertyConstraint(String propertyType, Type constraintType, - Gson gson, Object constraintJson) { + private static PropertyConstraint validateAndGetPropertyConstraint(String propertyType, Type constraintType, Gson gson, Object constraintJson) { PropertyConstraint propertyConstraint; try { propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType); } catch (ClassCastException | JsonParseException e) { - throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS_FORMAT, - constraintJson.toString()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS_FORMAT, constraintJson.toString()); } if (propertyConstraint != null && propertyConstraint instanceof ValidValuesConstraint) { try { ((ValidValuesConstraint) propertyConstraint).validateType(propertyType); } catch (ConstraintValueDoNotMatchPropertyTypeException e) { - BeEcompErrorManager.getInstance().logInternalFlowError("GetInitializedPropertyConstraint", - e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR); - throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS, - ConstraintType.VALID_VALUES.name(), + BeEcompErrorManager.getInstance() + .logInternalFlowError("GetInitializedPropertyConstraint", e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR); + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS, ConstraintType.VALID_VALUES.name(), ((ValidValuesConstraint) propertyConstraint).getValidValues().toString(), propertyType); } } @@ -407,41 +325,29 @@ public final class ImportUtils { } public static PropertyDefinition createModuleProperty(Map propertyValue) { - PropertyDefinition propertyDef = new PropertyDefinition(); setField(propertyValue, TypeUtils.ToscaTagNamesEnum.TYPE, propertyDef::setType); - setFieldBoolean(propertyValue, ToscaTagNamesEnum.REQUIRED, - req -> propertyDef.setRequired(Boolean.parseBoolean(req))); + setFieldBoolean(propertyValue, ToscaTagNamesEnum.REQUIRED, req -> propertyDef.setRequired(Boolean.parseBoolean(req))); setField(propertyValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, propertyDef::setDescription); - - setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, propertyDef.getType(), - propertyDef::setDefaultValue); - setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.VALUE, propertyDef.getType(), - propertyDef::setValue); - - setFieldBoolean(propertyValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, - pass -> propertyDef.setPassword(Boolean.parseBoolean(pass))); + setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, propertyDef.getType(), propertyDef::setDefaultValue); + setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.VALUE, propertyDef.getType(), propertyDef::setValue); + setFieldBoolean(propertyValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass))); setField(propertyValue, TypeUtils.ToscaTagNamesEnum.STATUS, propertyDef::setStatus); setSchema(propertyValue, propertyDef); setPropertyConstraints(propertyValue, propertyDef); - return propertyDef; } - private static void setJsonStringField(Map propertyValue, ToscaTagNamesEnum elementName, - String type, Consumer setter) { - Either eitherValue = findToscaElement(propertyValue, elementName, - ToscaElementTypeEnum.ALL); + private static void setJsonStringField(Map propertyValue, ToscaTagNamesEnum elementName, String type, Consumer setter) { + Either eitherValue = findToscaElement(propertyValue, elementName, ToscaElementTypeEnum.ALL); if (eitherValue.isLeft()) { String propertyJsonStringValue = getPropertyJsonStringValue(eitherValue.left().value(), type); setter.accept(propertyJsonStringValue); } } - public static Annotation createModuleAnnotation(Map annotationMap, - AnnotationTypeOperations annotationTypeOperations) { - String parsedAnnotationType = findFirstToscaStringElement(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE) - .left().value(); + public static Annotation createModuleAnnotation(Map annotationMap, AnnotationTypeOperations annotationTypeOperations) { + String parsedAnnotationType = findFirstToscaStringElement(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE).left().value(); AnnotationTypeDefinition annotationTypeObject = annotationTypeOperations.getLatestType(parsedAnnotationType); if (annotationTypeObject != null) { Annotation annotation = new Annotation(); @@ -464,11 +370,9 @@ public final class ImportUtils { 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 {} occurred upon import resource {}. ", name, - annotation.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils - .convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, - JsonPresentationFields.PROPERTY))); + log.debug("The property with invalid name {} occurred upon import resource {}. ", name, annotation.getName()); + result = Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY))); } PropertyDefinition propertyDefinition = entry.getValue(); propertyDefinition.setValue(propertyDefinition.getName()); @@ -478,16 +382,13 @@ public final class ImportUtils { } annotation.setProperties(propertiesList); } else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) { - result = Either - .right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties - .right() - .value(), JsonPresentationFields.PROPERTY))); + result = Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY))); } return result; } - public static InputDefinition createModuleInput(final Map inputValue, - final AnnotationTypeOperations annotationTypeOperations) { + public static InputDefinition createModuleInput(final Map inputValue, final AnnotationTypeOperations annotationTypeOperations) { return parseAnnotationsAndAddItToInput(createModuleInput(inputValue), inputValue, annotationTypeOperations); } @@ -496,66 +397,52 @@ public final class ImportUtils { setField(inputValue, TypeUtils.ToscaTagNamesEnum.TYPE, inputDef::setType); setFieldBoolean(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req))); setField(inputValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, inputDef::setDescription); - - setJsonStringField(inputValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, inputDef.getType(), - inputDef::setDefaultValue); - + setJsonStringField(inputValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, inputDef.getType(), inputDef::setDefaultValue); setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass))); setField(inputValue, TypeUtils.ToscaTagNamesEnum.STATUS, inputDef::setStatus); setField(inputValue, TypeUtils.ToscaTagNamesEnum.LABEL, inputDef::setLabel); setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden))); setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IMMUTABLE, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable))); - setSchema(inputValue, inputDef); setPropertyConstraints(inputValue, inputDef); return inputDef; } - public static InputDefinition parseAnnotationsAndAddItToInput(InputDefinition inputDef, - Map inputValue, + public static InputDefinition parseAnnotationsAndAddItToInput(InputDefinition inputDef, Map inputValue, AnnotationTypeOperations annotationTypeOperations) { Function elementGenByName = ImportUtils::createAnnotation; - Function, Annotation> func = annotation -> createModuleAnnotation(annotation, - annotationTypeOperations); - return getElements(inputValue, TypeUtils.ToscaTagNamesEnum.ANNOTATIONS, elementGenByName, func). - left().map(annotations -> modifyInputWithAnnotations(inputDef, annotations)). - left().on(err -> { - log.error("Parsing annotations or adding them to the PropertyDataDefinition object failed"); - return inputDef; - }); - } - - private static InputDefinition modifyInputWithAnnotations(InputDefinition inputDef, - Map annotationsMap) { + Function, Annotation> func = annotation -> createModuleAnnotation(annotation, annotationTypeOperations); + return getElements(inputValue, TypeUtils.ToscaTagNamesEnum.ANNOTATIONS, elementGenByName, func).left() + .map(annotations -> modifyInputWithAnnotations(inputDef, annotations)).left().on(err -> { + log.error("Parsing annotations or adding them to the PropertyDataDefinition object failed"); + return inputDef; + }); + } + + private static InputDefinition modifyInputWithAnnotations(InputDefinition inputDef, Map annotationsMap) { setAnnotationsName(annotationsMap); inputDef.setAnnotationsToInput(annotationsMap.values()); return inputDef; } public static AttributeDefinition createModuleAttribute(Map attributeMap) { - AttributeDefinition attributeDef = new AttributeDefinition(); setField(attributeMap, TypeUtils.ToscaTagNamesEnum.TYPE, attributeDef::setType); setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, attributeDef::setDescription); setField(attributeMap, TypeUtils.ToscaTagNamesEnum.STATUS, attributeDef::setStatus); - - setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(), - attributeDef::set_default); - + setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(), attributeDef::set_default); setEntrySchema(attributeMap, attributeDef); return attributeDef; } - private static void setSchema(final Map propertyValue, - final PropertyDefinition propertyDefinition) { + private static void setSchema(final Map propertyValue, final PropertyDefinition propertyDefinition) { final Either schemaElementRes = findEntrySchemaElement(propertyValue); if (schemaElementRes.isLeft()) { propertyDefinition.setSchema(getSchema(schemaElementRes.left().value())); } } - private static void setEntrySchema(final Map toscaJsonMap, - final AttributeDefinition attributeDefinition) { + private static void setEntrySchema(final Map toscaJsonMap, final AttributeDefinition attributeDefinition) { final Either schemaElementRes = findEntrySchemaElement(toscaJsonMap); if (schemaElementRes.isLeft()) { attributeDefinition.setEntry_schema(createEntrySchema(schemaElementRes.left().value())); @@ -592,62 +479,48 @@ public final class ImportUtils { return entrySchema; } - private static void setField(Map toscaJson, TypeUtils.ToscaTagNamesEnum tagName, - Consumer setter) { + private static void setField(Map toscaJson, TypeUtils.ToscaTagNamesEnum tagName, Consumer setter) { Either fieldStringValue = findFirstToscaStringElement(toscaJson, tagName); if (fieldStringValue.isLeft()) { setter.accept(fieldStringValue.left().value()); } - } - public static void setFieldBoolean(Map toscaJson, TypeUtils.ToscaTagNamesEnum tagName, - Consumer setter) { + public static void setFieldBoolean(Map toscaJson, TypeUtils.ToscaTagNamesEnum tagName, Consumer setter) { Either fieldStringValue = findFirstToscaBooleanElement(toscaJson, tagName); if (fieldStringValue.isLeft()) { setter.accept(fieldStringValue.left().value()); } - } - public static Either, ResultStatusEnum> getProperties( - Map toscaJson) { + public static Either, ResultStatusEnum> getProperties(Map toscaJson) { Function elementGenByName = ImportUtils::createProperties; Function, PropertyDefinition> func = ImportUtils::createModuleProperty; - return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.PROPERTIES, elementGenByName, func); - } public static Either, ResultStatusEnum> getAttributes(final Map toscaJson) { final Function elementGenByName = ImportUtils::createAttribute; final Function, AttributeDefinition> func = ImportUtils::createModuleAttribute; - return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func); } public static Either, ResultStatusEnum> getInputs(Map toscaJson, AnnotationTypeOperations annotationTypeOperations) { Function elementGenByName = ImportUtils::createInputs; - Function, InputDefinition> func = object -> createModuleInput(object, - annotationTypeOperations); - + Function, InputDefinition> func = object -> createModuleInput(object, annotationTypeOperations); return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, elementGenByName, func); - } public static Either, ResultStatusEnum> getInputs(final Map toscaJson) { - return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, ImportUtils::createInputs, - ImportUtils::createModuleInput); + return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, ImportUtils::createInputs, ImportUtils::createModuleInput); } - public static Either, ResultStatusEnum> getElements(Map toscaJson, - TypeUtils.ToscaTagNamesEnum elementTagName, + public static Either, ResultStatusEnum> getElements(Map toscaJson, TypeUtils.ToscaTagNamesEnum elementTagName, Function elementGenByName, Function, T> func) { Either, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, - elementTagName); + Either, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName); if (toscaAttributes.isLeft()) { Map jsonAttributes = toscaAttributes.left().value(); Map moduleAttributes = new HashMap<>(); @@ -655,8 +528,7 @@ public final class ImportUtils { while (propertiesNameValue.hasNext()) { Entry attributeNameValue = propertiesNameValue.next(); if (attributeNameValue.getValue() instanceof Map) { - @SuppressWarnings("unchecked") - T attribute = func.apply((Map) attributeNameValue.getValue()); + @SuppressWarnings("unchecked") T attribute = func.apply((Map) attributeNameValue.getValue()); if (attribute != null) { moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute); } @@ -668,15 +540,12 @@ public final class ImportUtils { if (moduleAttributes.size() > 0) { eitherResult = Either.left(moduleAttributes); } - } return eitherResult; - } private static AttributeDefinition createAttribute(String name) { AttributeDefinition attribute = new AttributeDefinition(); - attribute.setName(name); return attribute; } @@ -690,7 +559,6 @@ public final class ImportUtils { private static InputDefinition createInputs(String name) { InputDefinition input = new InputDefinition(); - input.setName(name); return input; } @@ -702,11 +570,8 @@ public final class ImportUtils { } public static Either, ResultStatusEnum> getHeatParameters(Map heatData, String artifactType) { - - Either, ResultStatusEnum> eitherResult = Either - .right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, - TypeUtils.ToscaTagNamesEnum.PARAMETERS); + Either, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, TypeUtils.ToscaTagNamesEnum.PARAMETERS); if (toscaProperties.isLeft()) { Map jsonProperties = toscaProperties.left().value(); List moduleProperties = new ArrayList<>(); @@ -715,8 +580,7 @@ public final class ImportUtils { 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( + @SuppressWarnings("unchecked") Either propertyStatus = createModuleHeatParameter( (Map) propertyNameValue.getValue()); if (propertyStatus.isRight()) { return Either.right(propertyStatus.right().value()); @@ -730,36 +594,29 @@ public final class ImportUtils { } else { addHeatParamDefinition(moduleProperties, propertyNameValue, false); } - } - if (!isEmpty(moduleProperties)) { eitherResult = Either.left(moduleProperties); } - } return eitherResult; - } - private static void addHeatParamDefinition(List moduleProperties, - Entry propertyNameValue, boolean isJson) { + 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) : StringEscapeUtils.escapeJava(String.valueOf(value))); + property.setDefaultValue(isJson ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value))); } property.setName(String.valueOf(propertyNameValue.getKey())); moduleProperties.add(property); } - private static Either createModuleHeatParameter( - Map propertyValue) { + private static Either createModuleHeatParameter(Map propertyValue) { HeatParameterDefinition propertyDef = new HeatParameterDefinition(); String type; - Either propertyFieldType = findFirstToscaStringElement(propertyValue, - TypeUtils.ToscaTagNamesEnum.TYPE); + Either propertyFieldType = findFirstToscaStringElement(propertyValue, TypeUtils.ToscaTagNamesEnum.TYPE); if (propertyFieldType.isLeft()) { type = propertyFieldType.left().value(); propertyDef.setType(type); @@ -771,20 +628,18 @@ public final class ImportUtils { if (propertyFieldDescription.isLeft()) { propertyDef.setDescription(propertyFieldDescription.left().value()); } - - Either propertyFieldDefaultVal = findToscaElement(propertyValue, - TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + Either propertyFieldDefaultVal = findToscaElement(propertyValue, TypeUtils.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) - : StringEscapeUtils.escapeJava(String.valueOf(value)); + String defaultValue = + type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value)); propertyDef.setDefaultValue(defaultValue); propertyDef.setCurrentValue(defaultValue); } - return Either.left(propertyDef); } @@ -799,16 +654,14 @@ public final class ImportUtils { return null; } ToscaPropertyType validType = ToscaPropertyType.isValidType(type); - if (validType == null || validType == ToscaPropertyType.JSON || validType == ToscaPropertyType.MAP - || validType == ToscaPropertyType.LIST) { + if (validType == null || validType == ToscaPropertyType.JSON || validType == ToscaPropertyType.MAP || validType == 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 + * 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 @@ -825,4 +678,57 @@ public final class ImportUtils { } } } + + 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, INVALID_ATTRIBUTE_NAME + } + + public enum ToscaElementTypeEnum { + BOOLEAN, STRING, MAP, LIST, ALL + } + + 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 class YamlLoader extends YamlProcessor { + + public Yaml getStrictYamlLoader() { + return createYaml(); + } + } + + public static class Constants { + + public static final String FIRST_NON_CERTIFIED_VERSION = "0.1"; + public static final String VENDOR_NAME = "ONAP (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 static final String ESCAPED_DOUBLE_QUOTE = "\""; + public static final String QUOTE = "'"; + public static final String VF_DESCRIPTION = "Nested VF in service"; + + private Constants() { + } + } } 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 2f43a5b736..da84921a5b 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 @@ -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. @@ -19,10 +19,18 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +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.Objects; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.collections4.MapUtils; @@ -76,22 +84,11 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -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.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - @org.springframework.stereotype.Component("inputsBusinessLogic") public class InputsBusinessLogic extends BaseBusinessLogic { private static final String CREATE_INPUT = "CreateInput"; private static final String UPDATE_INPUT = "UpdateInput"; - private static final Logger log = Logger.getLogger(InputsBusinessLogic.class); private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}"; private static final String GET_PROPERTIES_BY_INPUT = "get Properties by input"; @@ -101,23 +98,19 @@ public class InputsBusinessLogic extends BaseBusinessLogic { private static final String GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT = "Going to execute rollback on update input."; private static final String GOING_TO_EXECUTE_COMMIT_ON_UPDATE_INPUT = "Going to execute commit on update input."; private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(InputsBusinessLogic.class.getName()); - private final PropertyDeclarationOrchestrator propertyDeclarationOrchestrator; private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; private final DataTypeBusinessLogic dataTypeBusinessLogic; @Autowired - public InputsBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - PropertyDeclarationOrchestrator propertyDeclarationOrchestrator, - ComponentInstanceBusinessLogic componentInstanceBusinessLogic, DataTypeBusinessLogic dataTypeBusinessLogic, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public InputsBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + PropertyDeclarationOrchestrator propertyDeclarationOrchestrator, + ComponentInstanceBusinessLogic componentInstanceBusinessLogic, DataTypeBusinessLogic dataTypeBusinessLogic, + ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.propertyDeclarationOrchestrator = propertyDeclarationOrchestrator; this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; this.dataTypeBusinessLogic = dataTypeBusinessLogic; @@ -131,59 +124,50 @@ public class InputsBusinessLogic extends BaseBusinessLogic { * @return */ public Either, ResponseFormat> getInputs(String userId, String componentId) { - validateUserExists(userId); - ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); filters.setIgnoreInputs(false); - - Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ + 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(); List inputs = component.getInputs(); - return Either.left(inputs); - } - public Either, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) { - + public Either, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, + String componentInstanceId) { validateUserExists(userId); ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); filters.setIgnoreInputs(false); filters.setIgnoreComponentInstances(false); filters.setIgnoreComponentInstancesInputs(false); - - Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ + 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)){ + if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) { ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,component.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"Failed to found component instance inputs componentInstanceId: {}",componentInstanceId); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "Failed to found component instance inputs componentInstanceId: {}", componentInstanceId); return Either.right(componentsUtils.getResponseFormat(actionStatus)); } - Map> ciInputs = - Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap()); - - // Set Constraints on Input - MapUtils.emptyIfNull(ciInputs).values() - .forEach(inputs -> ListUtils.emptyIfNull(inputs) - .forEach(input -> input.setConstraints(setInputConstraint(input)))); + Map> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs()) + .orElse(Collections.emptyMap()); + // Set Constraints on Input + MapUtils.emptyIfNull(ciInputs).values() + .forEach(inputs -> ListUtils.emptyIfNull(inputs).forEach(input -> input.setConstraints(setInputConstraint(input)))); return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList())); } @@ -195,59 +179,47 @@ public class InputsBusinessLogic extends BaseBusinessLogic { * @param inputId * @return */ - - public Either, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) { + public Either, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, + String instanceId, String inputId) { validateUserExists(userId); String parentId = componentId; org.openecomp.sdc.be.model.Component component; ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); filters.setIgnoreComponentInstances(false); - - if(!instanceId.equals(inputId)){ - - - Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); - - if(getComponentEither.isRight()){ + 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()){ + 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()){ + 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()){ + 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 String updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map dataTypes) { @@ -255,7 +227,6 @@ public class InputsBusinessLogic extends BaseBusinessLogic { 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) { @@ -270,14 +241,14 @@ public class InputsBusinessLogic extends BaseBusinessLogic { innerType = propDef.getType(); } // Specific Update Logic - - Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes); - + Either isValid = propertyOperation + .validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes); String newValue = newInput.getDefaultValue(); if (isValid.isRight()) { Boolean res = isValid.right().value(); if (Boolean.FALSE.equals(res)) { - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse( + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))); } } else { Object object = isValid.left().value(); @@ -292,25 +263,22 @@ public class InputsBusinessLogic extends BaseBusinessLogic { return componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst().orElse(null); } - public Either, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId, List inputs, String userId, boolean shouldLockComp, boolean inTransaction) { - + 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 { validateUserExists(userId); - ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreInputs(false); componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreProperties(false); - componentParametersView.setIgnoreComponentInstancesProperties(false); - componentParametersView.setIgnoreComponentInstances(false); - + componentParametersView.setIgnoreProperties(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnoreComponentInstances(false); component = validateComponentExists(componentId, componentType, componentParametersView); - if (shouldLockComp) { try { lockComponent(component, UPDATE_INPUT); @@ -320,21 +288,17 @@ public class InputsBusinessLogic extends BaseBusinessLogic { return result; } } - //Validate value and Constraint of input - Either constraintValidatorResponse = validateInputValueConstraint(inputs); + Either constraintValidatorResponse = validateInputValueConstraint(inputs); if (constraintValidatorResponse.isRight()) { - log.error("Failed validation value and constraint of property: {}", - constraintValidatorResponse.right().value()); + log.error("Failed validation value and constraint of property: {}", constraintValidatorResponse.right().value()); return Either.right(constraintValidatorResponse.right().value()); } - validateCanWorkOnComponent(component, userId); Map dataTypes; dataTypes = getAllDataTypes(applicationDataTypeCache); - List componentsOldInputs = Optional.ofNullable(component.getInputs()).orElse(Collections.emptyList()); - for (InputDefinition newInput: inputs) { + for (InputDefinition newInput : inputs) { InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput); if (currInput == null) { ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND; @@ -350,7 +314,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { currInput.setRequired(newInput.isRequired()); } Either status = toscaOperationFacade.updateInputOfComponent(component, currInput); - if(status.isRight()){ + if (status.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); return result; @@ -362,37 +326,32 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } catch (ComponentException e) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT); unlockRollbackWithException(component, e); - } catch (Exception e){ + } catch (Exception e) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT); unlockRollbackWithException(component, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR)); } log.debug(GOING_TO_EXECUTE_COMMIT_ON_UPDATE_INPUT); unlockWithCommit(component); return result; - } private Either validateInputValueConstraint(List inputs) { - PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil = - PropertyValueConstraintValidationUtil.getInstance(); - List inputDefinitions = new ArrayList<>(); - for (InputDefinition inputDefinition : inputs) { - InputDefinition inputDef = new InputDefinition(); - inputDefinition.setDefaultValue(inputDefinition.getDefaultValue()); - inputDefinition.setInputPath(inputDefinition.getSubPropertyInputPath()); - inputDefinition.setType(inputDefinition.getType()); - if (Objects.nonNull(inputDefinition.getParentPropertyType())) { - ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty(); - propertyDefinition.setType(inputDefinition.getParentPropertyType()); - - inputDefinition.setProperties(Collections.singletonList(propertyDefinition)); - } - - inputDefinitions.add(inputDef); - } - - return propertyValueConstraintValidationUtil.validatePropertyConstraints(inputDefinitions, applicationDataTypeCache); - } + PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil = PropertyValueConstraintValidationUtil.getInstance(); + List inputDefinitions = new ArrayList<>(); + for (InputDefinition inputDefinition : inputs) { + InputDefinition inputDef = new InputDefinition(); + inputDefinition.setDefaultValue(inputDefinition.getDefaultValue()); + inputDefinition.setInputPath(inputDefinition.getSubPropertyInputPath()); + inputDefinition.setType(inputDefinition.getType()); + if (Objects.nonNull(inputDefinition.getParentPropertyType())) { + ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty(); + propertyDefinition.setType(inputDefinition.getParentPropertyType()); + inputDefinition.setProperties(Collections.singletonList(propertyDefinition)); + } + inputDefinitions.add(inputDef); + } + return propertyValueConstraintValidationUtil.validatePropertyConstraints(inputDefinitions, applicationDataTypeCache); + } public Either, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) { validateUserExists(userId); @@ -403,59 +362,46 @@ public class InputsBusinessLogic extends BaseBusinessLogic { filters.setIgnoreInputs(false); filters.setIgnoreComponentInstancesInputs(false); filters.setIgnoreProperties(false); - - Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - - if(getComponentEither.isRight()){ + 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)); - } component = getComponentEither.left().value(); - Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); - if(!op.isPresent()){ + 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)); } - return Either.left(componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId)); - } @Override - public Either, ResponseFormat> declareProperties(String userId, String componentId, - ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) { - + public Either, ResponseFormat> declareProperties(String userId, String componentId, ComponentTypeEnum componentTypeEnum, + ComponentInstInputsMap componentInstInputsMap) { return createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); } - public Either, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) { - + 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 { validateUserExists(userId); - component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp); - - result = propertyDeclarationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi) - .left() - .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate)) - .right() - .map(componentsUtils::getResponseFormat); - + result = propertyDeclarationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi).left() + .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate)).right() + .map(componentsUtils::getResponseFormat); return result; - } catch (ByResponseFormatComponentException e) { log.error("#createMultipleInputs: Exception thrown: ", e); result = Either.right(e.getResponseFormat()); return result; } finally { - if (!inTransaction) { if (result == null || result.isRight()) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); @@ -469,29 +415,25 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - } } /** * Creates a list input with a data type which has properties specified. * - * @param userId User ID - * @param componentId Component ID - * @param componentType Component type + * @param userId User ID + * @param componentId Component ID + * @param componentType Component type * @param componentListInput Properties to be declared and input to be created - * @param shouldLockComp true if the component should be locked - * @param inTransaction true if already in transaction + * @param shouldLockComp true if the component should be locked + * @param inTransaction true if already in transaction */ - public Either, ResponseFormat> createListInput(String userId, String componentId, - ComponentTypeEnum componentType, ComponentInstListInput componentListInput, boolean shouldLockComp, - boolean inTransaction) { - + public Either, ResponseFormat> createListInput(String userId, String componentId, ComponentTypeEnum componentType, + ComponentInstListInput componentListInput, boolean shouldLockComp, + boolean inTransaction) { Either, ResponseFormat> result = null; org.openecomp.sdc.be.model.Component component = null; - log.trace("#createListInput: enter"); - try { /* check if user exists */ validateUserExists(userId); @@ -608,22 +550,24 @@ public class InputsBusinessLogic extends BaseBusinessLogic { return dataType; } - private Either, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId, List inputsToCreate) { + private Either, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId, + List inputsToCreate) { Map inputsToPersist = MapUtil.toMap(inputsToCreate, InputDefinition::getName); assignOwnerIdToInputs(userId, inputsToPersist); - inputsToPersist.values() - .forEach(input -> input.setConstraints(componentInstanceBusinessLogic.setInputConstraint(input))); + inputsToPersist.values() + .forEach(input -> input.setConstraints(componentInstanceBusinessLogic.setInputConstraint(input))); return toscaOperationFacade.addInputsToComponent(inputsToPersist, cmptId) - .left() - .map(persistedInputs -> inputsToCreate); + .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) { + public Either, ResponseFormat> createInputsInGraph(Map inputs, + org.openecomp.sdc.be.model.Component component) { List resourceProperties = component.getInputs(); @@ -634,22 +578,24 @@ public class InputsBusinessLogic extends BaseBusinessLogic { inputDefinition.getValue().setName(inputName); Either preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes); - if(preparedInputEither.isRight()){ + if (preparedInputEither.isRight()) { return Either.right(preparedInputEither.right().value()); } } if (resourceProperties != null) { - Map generatedInputs = resourceProperties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i)); + Map generatedInputs = resourceProperties.stream() + .collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i)); Either, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs); - if(mergeEither.isRight()){ + if (mergeEither.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value())); } inputs = mergeEither.left().value(); } - Either, StorageOperationStatus> associateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId()); - if(associateInputsEither.isRight()){ + Either, StorageOperationStatus> associateInputsEither = toscaOperationFacade + .createAndAssociateInputs(inputs, component.getUniqueId()); + if (associateInputsEither.isRight()) { log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), associateInputsEither.right().value()); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(associateInputsEither.right().value()))); @@ -658,12 +604,13 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } private Either, ResponseFormat> createListInputsInGraph(Map inputs, - Map privateDataTypes, org.openecomp.sdc.be.model.Component component) { + Map privateDataTypes, + org.openecomp.sdc.be.model.Component component) { log.trace("#createListInputsInGraph: enter"); Map dataTypes = getAllDataTypes( - applicationDataTypeCache); + applicationDataTypeCache); dataTypes.putAll(privateDataTypes); for (Map.Entry inputDefinition : inputs.entrySet()) { @@ -698,99 +645,86 @@ public class InputsBusinessLogic extends BaseBusinessLogic { * @return */ public InputDefinition deleteInput(String componentId, String userId, String inputId) { - Either deleteEither = null; if (log.isDebugEnabled()) { log.debug("Going to delete input id: {}", inputId); } - validateUserExists(userId); - ComponentParametersView componentParametersView = getBaseComponentParametersView(); componentParametersView.setIgnoreInterfaces(false); componentParametersView.setIgnoreDataType(false); componentParametersView.setIgnoreProperties(false); - - Either componentEither = - toscaOperationFacade.getToscaElement(componentId, componentParametersView); + Either componentEither = toscaOperationFacade + .getToscaElement(componentId, componentParametersView); if (componentEither.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value())); } 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(); + // filter by ID + filter(input -> input.getUniqueId().equals(inputId)). + // Get the input + findAny(); if (!optionalInput.isPresent()) { throw new ByActionStatusComponentException(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId); } - InputDefinition inputForDelete = optionalInput.get(); - // Lock component lockComponent(componentId, component, "deleteInput"); // Delete input operations boolean failed = false; try { - StorageOperationStatus status = - toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); + StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); if (status != StorageOperationStatus.OK) { log.debug("Component id: {} delete input id: {} failed", componentId, inputId); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName()); } - - if (BooleanUtils.isTrue(inputForDelete.getIsDeclaredListInput())){ + if (BooleanUtils.isTrue(inputForDelete.getIsDeclaredListInput())) { deleteEither = deleteListInput(componentId, inputId, component, inputForDelete, status); - if (deleteEither.isRight()){ + if (deleteEither.isRight()) { throw new ByResponseFormatComponentException(deleteEither.right().value()); } return deleteEither.left().value(); } - - StorageOperationStatus storageOperationStatus = - propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete); + StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete); if (storageOperationStatus != StorageOperationStatus.OK) { log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName()); } - return inputForDelete; - }catch (ComponentException e){ + return inputForDelete; + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { unlockComponent(failed, component); } } private Either deleteListInput(String componentId, String inputId, - org.openecomp.sdc.be.model.Component component, - InputDefinition inputForDelete, StorageOperationStatus status) { + org.openecomp.sdc.be.model.Component component, InputDefinition inputForDelete, + StorageOperationStatus status) { // the input is created by 'Declare List'. - // need to 1. undeclare properties, 2. delete input, 3. delete private data type - StorageOperationStatus storageOperationStatus = - propertyDeclarationOrchestrator.unDeclarePropertiesAsListInputs(component, inputForDelete); + // need to 1. undeclare properties, 2. delete input, 3. delete private data type + StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsListInputs(component, inputForDelete); if (storageOperationStatus != StorageOperationStatus.OK) { log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(status), component.getName())); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); } - Either deleteResult = - dataTypeBusinessLogic.deletePrivateDataType(component, inputForDelete.getSchemaType()); + Either deleteResult = dataTypeBusinessLogic + .deletePrivateDataType(component, inputForDelete.getSchemaType()); if (deleteResult.isRight()) { log.debug("Component id: {} delete datatype name: {} failed", componentId, inputForDelete.getSchemaType()); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(deleteResult.right().value()), component.getName())); + return Either.right( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteResult.right().value()), component.getName())); } log.trace("deleteInput: deletePrivateDataType (OK)"); return Either.left(inputForDelete); } - private Either prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map dataTypes) { - + private Either prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, + Map dataTypes) { // validate input default values Either defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes); if (defaultValuesValidation.isRight()) { @@ -818,10 +752,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { return Either.left(newInputDefinition); } - public Either getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) { + public Either getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, + boolean inTransaction) { Either result = null; try { - validateUserExists(userId); ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); @@ -830,41 +764,29 @@ public class InputsBusinessLogic extends BaseBusinessLogic { filters.setIgnoreComponentInstancesInputs(false); filters.setIgnoreComponentInstancesProperties(false); filters.setIgnoreProperties(false); - Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ + 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()){ + 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) ; - + List inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId); resObj.setInputs(inputCIInput); - - - List inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId) ; - + List inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId); resObj.setProperties(inputProps); - - result = Either.left(resObj); - return result; - } finally { - if (!inTransaction) { - if (result == null || result.isRight()) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); janusGraphDao.rollback(); @@ -872,69 +794,48 @@ public class InputsBusinessLogic extends BaseBusinessLogic { log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP); janusGraphDao.commit(); } - } - } - } - public Either, ResponseFormat> addInputToComponent(String componentId, - String inputName, - InputDefinition newInputDefinition, - String userId) { + public Either, ResponseFormat> addInputToComponent(String componentId, String inputName, + InputDefinition newInputDefinition, String userId) { Either, ResponseFormat> result = null; - validateUserExists(userId); - - Either serviceElement = - toscaOperationFacade.getToscaElement(componentId); + Either serviceElement = toscaOperationFacade.getToscaElement(componentId); if (serviceElement.isRight()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); return result; } - Component component = serviceElement.left().value(); NodeTypeEnum nodeType = component.getComponentType().getNodeType(); - StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType); if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance() - .logBeFailedLockObjectError(CREATE_INPUT, nodeType.name().toLowerCase(), componentId); + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_INPUT, nodeType.name().toLowerCase(), componentId); log.info("Failed to lock component {}. Error - {}", componentId, lockResult); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } - try { if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return result; } - List inputs = component.getInputs(); - if (CollectionUtils.isEmpty(inputs)) { inputs = new ArrayList<>(); } - if (isInputExistInComponent(inputs, inputName)) { - - result = Either.right(componentsUtils.getResponseFormat(ActionStatus - .INPUT_ALREADY_EXIST, inputName)); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_ALREADY_EXIST, inputName)); return result; } - Map allDataTypes = getAllDataTypes(applicationDataTypeCache); - // validate input default values - Either defaultValuesValidation = validatePropertyDefaultValue( - newInputDefinition, allDataTypes); + Either defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, allDataTypes); if (defaultValuesValidation.isRight()) { result = Either.right(defaultValuesValidation.right().value()); return result; } - // convert Input ToscaPropertyType type = getType(newInputDefinition.getType()); if (type != null) { @@ -949,24 +850,18 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } } if (newInputDefinition.getDefaultValue() != null) { - String convertedValue = converter - .convert(newInputDefinition.getDefaultValue(), innerType, allDataTypes); + String convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, allDataTypes); newInputDefinition.setDefaultValue(convertedValue); } } - newInputDefinition.setMappedToComponentProperty(false); - Either addInputEither = - toscaOperationFacade.addInputToComponent(inputName, newInputDefinition, component); - + Either addInputEither = toscaOperationFacade + .addInputToComponent(inputName, newInputDefinition, component); if (addInputEither.isRight()) { - log.info("Failed to add new input {}. Error - {}", componentId, - addInputEither.right().value()); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus - .GENERAL_ERROR)); + log.info("Failed to add new input {}. Error - {}", componentId, addInputEither.right().value()); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } - result = Either.left(new EntryData<>(inputName, newInputDefinition)); return result; } finally { @@ -977,8 +872,6 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } private boolean isInputExistInComponent(List inputs, String inputName) { - return CollectionUtils.isNotEmpty(inputs) && - inputs.stream().anyMatch(input -> input.getName().equals(inputName)); + return CollectionUtils.isNotEmpty(inputs) && inputs.stream().anyMatch(input -> input.getName().equals(inputName)); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java index 71005ef0f0..62e6ce5182 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.QUOTE; @@ -64,7 +63,6 @@ import org.springframework.stereotype.Component; public class InterfaceDefinitionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceDefinitionHandler.class); - private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic; public InterfaceDefinitionHandler(final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) { @@ -78,9 +76,7 @@ public class InterfaceDefinitionHandler { * @return an interface definition representation */ public InterfaceDefinition create(final Map interfaceDefinitionToscaMap) { - final InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); - if (interfaceDefinitionToscaMap.containsKey(TYPE.getElementName())) { final Object typeObj = interfaceDefinitionToscaMap.get(TYPE.getElementName()); if (!(typeObj instanceof String)) { @@ -90,11 +86,10 @@ public class InterfaceDefinitionHandler { interfaceDefinition.setType(type); interfaceDefinition.setUniqueId(type.toLowerCase()); } - final Map inputDefinitionMap = handleInputs(interfaceDefinitionToscaMap); if (!inputDefinitionMap.isEmpty()) { - final Map collect = inputDefinitionMap.entrySet().stream(). - collect(Collectors.toMap(Entry::getKey, value -> new InputDataDefinition(value.getValue()))); + final Map collect = inputDefinitionMap.entrySet().stream() + .collect(Collectors.toMap(Entry::getKey, value -> new InputDataDefinition(value.getValue()))); interfaceDefinition.setInputs(collect); } final Map operationMap; @@ -109,88 +104,63 @@ public class InterfaceDefinitionHandler { validateOperations(interfaceDefinition.getType(), operationMap); interfaceDefinition.setOperations(operationMap); } - return interfaceDefinition; } - private void validateOperations(final String interfaceType, - final Map operationMap) { + private void validateOperations(final String interfaceType, final Map operationMap) { if (MapUtils.isEmpty(operationMap)) { return; } - Either, ResponseFormat> interfaceDefinitionMapEither = - interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(); + Either, ResponseFormat> interfaceDefinitionMapEither = interfaceOperationBusinessLogic + .getAllInterfaceLifecycleTypes(); if (interfaceDefinitionMapEither.isRight() || MapUtils.isEmpty(interfaceDefinitionMapEither.left().value())) { throw new ByActionStatusComponentException(ActionStatus.INTERFACE_UNKNOWN, interfaceType); } - final Map interfaceDefinitionMap = interfaceDefinitionMapEither.left().value(); final Optional interfaceDefinitionOptional = interfaceDefinitionMap.entrySet().stream() - .filter(interfaceDefinitionEntry -> interfaceDefinitionEntry.getKey().equalsIgnoreCase(interfaceType)) - .map(Entry::getValue).findFirst(); + .filter(interfaceDefinitionEntry -> interfaceDefinitionEntry.getKey().equalsIgnoreCase(interfaceType)).map(Entry::getValue).findFirst(); if (interfaceDefinitionOptional.isEmpty()) { throw new ByActionStatusComponentException(ActionStatus.INTERFACE_UNKNOWN, interfaceType); } final InterfaceDefinition interfaceDefinition = interfaceDefinitionOptional.get(); operationMap.keySet().forEach(operation1 -> { if (!interfaceDefinition.hasOperation(operation1)) { - throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_DEFINED, - operation1, interfaceType); + throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_DEFINED, operation1, interfaceType); } }); } - private Map handleOperations( - final Map interfaceDefinitionToscaMap) { + private Map handleOperations(final Map interfaceDefinitionToscaMap) { if (!interfaceDefinitionToscaMap.containsKey(OPERATIONS.getElementName())) { return Collections.emptyMap(); } - final Map operationMap = - (Map) interfaceDefinitionToscaMap.get(OPERATIONS.getElementName()); + final Map operationMap = (Map) interfaceDefinitionToscaMap.get(OPERATIONS.getElementName()); return operationMap.entrySet().stream() - .map(interfaceEntry -> createOperation(interfaceEntry.getKey(), - (Map) interfaceEntry.getValue())) - .collect( - Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition)); + .map(interfaceEntry -> createOperation(interfaceEntry.getKey(), (Map) interfaceEntry.getValue())) + .collect(Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition)); } - private Map handleLegacyOperations( - final Map interfaceDefinitionToscaMap) { + private Map handleLegacyOperations(final Map interfaceDefinitionToscaMap) { final List notALegacyOperationEntry = Arrays - .asList(OPERATIONS.getElementName(), - TYPE.getElementName(), - INPUTS.getElementName(), - NOTIFICATIONS.getElementName()); - return interfaceDefinitionToscaMap.entrySet().stream() - .filter(interfaceEntry -> !notALegacyOperationEntry.contains(interfaceEntry.getKey())) - .map(interfaceEntry -> createOperation(interfaceEntry.getKey(), - (Map) interfaceEntry.getValue())) - .collect( - Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition)); + .asList(OPERATIONS.getElementName(), TYPE.getElementName(), INPUTS.getElementName(), NOTIFICATIONS.getElementName()); + return interfaceDefinitionToscaMap.entrySet().stream().filter(interfaceEntry -> !notALegacyOperationEntry.contains(interfaceEntry.getKey())) + .map(interfaceEntry -> createOperation(interfaceEntry.getKey(), (Map) interfaceEntry.getValue())) + .collect(Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition)); } - - private OperationDataDefinition createOperation(final String operationName, - final Map operationDefinitionMap) { + private OperationDataDefinition createOperation(final String operationName, final Map operationDefinitionMap) { final OperationDataDefinition operation = new OperationDataDefinition(); operation.setUniqueId(UUID.randomUUID().toString()); operation.setName(operationName); - - operation.setImplementation( - handleOperationImplementation(operationDefinitionMap) - .orElse(new ArtifactDataDefinition()) - ); + operation.setImplementation(handleOperationImplementation(operationDefinitionMap).orElse(new ArtifactDataDefinition())); if (operationDefinitionMap.containsKey(INPUTS.getElementName())) { - final Map interfaceInputs = - (Map) operationDefinitionMap.get(INPUTS.getElementName()); + final Map interfaceInputs = (Map) operationDefinitionMap.get(INPUTS.getElementName()); operation.setInputs(handleInterfaceOperationInputs(interfaceInputs)); } - return operation; } - private ListDataDefinition handleInterfaceOperationInputs( - final Map interfaceInputs) { + private ListDataDefinition handleInterfaceOperationInputs(final Map interfaceInputs) { final ListDataDefinition inputs = new ListDataDefinition<>(); for (final Entry interfaceInput : interfaceInputs.entrySet()) { final OperationInputDefinition operationInput = new OperationInputDefinition(); @@ -198,10 +168,9 @@ public class InterfaceDefinitionHandler { operationInput.setInputId(operationInput.getUniqueId()); operationInput.setName(interfaceInput.getKey()); if (interfaceInput.getValue() instanceof Map) { - final LinkedHashMap inputPropertyValue = - (LinkedHashMap) interfaceInput.getValue(); - LOGGER.info("createModuleInterface: i interfaceInput.getKey() {}, {} , {} ", - interfaceInput.getKey(), inputPropertyValue.keySet(), inputPropertyValue.values()); + final LinkedHashMap inputPropertyValue = (LinkedHashMap) interfaceInput.getValue(); + LOGGER.info("createModuleInterface: i interfaceInput.getKey() {}, {} , {} ", interfaceInput.getKey(), inputPropertyValue.keySet(), + inputPropertyValue.values()); if (inputPropertyValue.get(TYPE.getElementName()) != null) { operationInput.setType(inputPropertyValue.get(TYPE.getElementName()).toString()); } @@ -209,8 +178,7 @@ public class InterfaceDefinitionHandler { operationInput.setDescription(inputPropertyValue.get(DESCRIPTION.getElementName()).toString()); } if (inputPropertyValue.get(REQUIRED.getElementName()) != null) { - operationInput.setRequired( - Boolean.getBoolean(inputPropertyValue.get(REQUIRED.getElementName()).toString())); + operationInput.setRequired(Boolean.getBoolean(inputPropertyValue.get(REQUIRED.getElementName()).toString())); } if (inputPropertyValue.get(DEFAULT.getElementName()) != null) { operationInput.setToscaDefaultValue(inputPropertyValue.get(DEFAULT.getElementName()).toString()); @@ -218,7 +186,6 @@ public class InterfaceDefinitionHandler { if (inputPropertyValue.get(STATUS.getElementName()) != null) { operationInput.setStatus(inputPropertyValue.get(STATUS.getElementName()).toString()); } - } else if (interfaceInput.getValue() instanceof String) { final String value = (String) interfaceInput.getValue(); operationInput.setDefaultValue(value); @@ -230,8 +197,7 @@ public class InterfaceDefinitionHandler { return inputs; } - private Optional handleOperationImplementation( - final Map operationDefinitionMap) { + private Optional handleOperationImplementation(final Map operationDefinitionMap) { if (!operationDefinitionMap.containsKey(IMPLEMENTATION.getElementName())) { return Optional.empty(); } @@ -249,14 +215,10 @@ public class InterfaceDefinitionHandler { if (!interfaceDefinitionToscaMap.containsKey(INPUTS.getElementName())) { return Collections.emptyMap(); } - - final Either, ResultStatusEnum> inputMapEither = - ImportUtils.getInputs(interfaceDefinitionToscaMap); + final Either, ResultStatusEnum> inputMapEither = ImportUtils.getInputs(interfaceDefinitionToscaMap); if (inputMapEither.isRight()) { return Collections.emptyMap(); } - return inputMapEither.left().value(); } - } 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 f1b4442e18..1c5411434f 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; @@ -46,18 +45,15 @@ import org.springframework.stereotype.Component; @Component("interfaceLifecycleTypeImportManager") public class InterfaceLifecycleTypeImportManager { + private static final Logger log = Logger.getLogger(InterfaceLifecycleTypeImportManager.class); @Resource private IInterfaceLifecycleOperation interfaceLifecycleOperation; - @Resource private ComponentsUtils componentsUtils; @Resource private CommonImportManager commonImportManager; - private static final Logger log = Logger.getLogger(InterfaceLifecycleTypeImportManager.class); - public Either, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) { - Either, ActionStatus> interfaces = createInterfaceTypeFromYml(interfaceLifecycleTypesYml); if (interfaces.isRight()) { ActionStatus status = interfaces.right().value(); @@ -65,12 +61,10 @@ public class InterfaceLifecycleTypeImportManager { return Either.right(responseFormat); } return createInterfacesByDao(interfaces.left().value()); - } private Either, ActionStatus> createInterfaceTypeFromYml(final String interfaceTypesYml) { return commonImportManager.createElementTypesFromYml(interfaceTypesYml, this::createInterfaceDefinition); - } private Either, ResponseFormat> createInterfacesByDao(List interfacesToCreate) { @@ -80,18 +74,17 @@ public class InterfaceLifecycleTypeImportManager { 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()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), + interfaceDef.getType()); eitherResult = Either.right(responseFormat); stopDao = true; } - } else { createdInterfaces.add(dataModelResponse.left().value()); } @@ -102,8 +95,7 @@ public class InterfaceLifecycleTypeImportManager { return eitherResult; } - private InterfaceDefinition createInterfaceDefinition(final String interfaceDefinition, - final Map toscaJson) { + private InterfaceDefinition createInterfaceDefinition(final String interfaceDefinition, final Map toscaJson) { final InterfaceDefinition interfaceDef = new InterfaceDefinition(); interfaceDef.setType(interfaceDefinition); final Object descriptionObj = toscaJson.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()); @@ -118,25 +110,19 @@ public class InterfaceLifecycleTypeImportManager { if (versionObj instanceof String) { interfaceDef.setVersion((String) versionObj); } - final Object metadataObj = toscaJson.get(ToscaTagNamesEnum.METADATA.getElementName()); if (metadataObj instanceof Map) { interfaceDef.setToscaPresentationValue(JsonPresentationFields.METADATA, metadataObj); } - final Map operationsMap; if (toscaJson.containsKey(ToscaTagNamesEnum.OPERATIONS.getElementName())) { operationsMap = (Map) toscaJson.get(ToscaTagNamesEnum.OPERATIONS.getElementName()); } else { final List entitySchemaEntryList = Arrays - .asList(ToscaTagNamesEnum.DERIVED_FROM.getElementName(), - ToscaTagNamesEnum.DESCRIPTION.getElementName(), - ToscaTagNamesEnum.VERSION.getElementName(), - ToscaTagNamesEnum.METADATA.getElementName(), - ToscaTagNamesEnum.INPUTS.getElementName(), - ToscaTagNamesEnum.NOTIFICATIONS.getElementName()); - operationsMap = toscaJson.entrySet().stream() - .filter(interfaceEntry -> !entitySchemaEntryList.contains(interfaceEntry.getKey())) + .asList(ToscaTagNamesEnum.DERIVED_FROM.getElementName(), ToscaTagNamesEnum.DESCRIPTION.getElementName(), + ToscaTagNamesEnum.VERSION.getElementName(), ToscaTagNamesEnum.METADATA.getElementName(), + ToscaTagNamesEnum.INPUTS.getElementName(), ToscaTagNamesEnum.NOTIFICATIONS.getElementName()); + operationsMap = toscaJson.entrySet().stream().filter(interfaceEntry -> !entitySchemaEntryList.contains(interfaceEntry.getKey())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); } interfaceDef.setOperationsMap(handleOperations(operationsMap)); @@ -148,8 +134,7 @@ public class InterfaceLifecycleTypeImportManager { return Collections.emptyMap(); } return operationsToscaEntry.entrySet().stream() - .collect(Collectors.toMap(Entry::getKey, - operationEntry -> createOperation((Map) operationEntry.getValue()))); + .collect(Collectors.toMap(Entry::getKey, operationEntry -> createOperation((Map) operationEntry.getValue()))); } private Operation createOperation(final Map toscaOperationMap) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java index 3aabe82db5..e23818c957 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java @@ -13,12 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package org.openecomp.sdc.be.components.impl; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedCapabilityPropertyDefaultValue; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedInputPropertyDefaultValue; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedOutputDefaultValue; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationFromInterfaceDefinition; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput; +import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityFromAllCapProps; +import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty; +import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF; + import com.google.gson.Gson; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -57,147 +76,101 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedCapabilityPropertyDefaultValue; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedInputPropertyDefaultValue; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedOutputDefaultValue; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationFromInterfaceDefinition; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput; -import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityFromAllCapProps; -import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty; -import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF; - @Component("interfaceOperationBusinessLogic") public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceOperationBusinessLogic.class); - private static final String EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION = - "Exception occurred during {}. Response is {}"; + private static final String EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION = "Exception occurred during {}. Response is {}"; private static final String DELETE_INTERFACE_OPERATION = "deleteInterfaceOperation"; private static final String GET_INTERFACE_OPERATION = "getInterfaceOperation"; private static final String CREATE_INTERFACE_OPERATION = "createInterfaceOperation"; private static final String UPDATE_INTERFACE_OPERATION = "updateInterfaceOperation"; - private final ArtifactCassandraDao artifactCassandraDao; private final InterfaceOperationValidation interfaceOperationValidation; @Autowired - public InterfaceOperationBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactCassandraDao artifactCassandraDao, - InterfaceOperationValidation interfaceOperationValidation, ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public InterfaceOperationBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactCassandraDao artifactCassandraDao, InterfaceOperationValidation interfaceOperationValidation, + ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.artifactCassandraDao = artifactCassandraDao; this.interfaceOperationValidation = interfaceOperationValidation; } - public Either, ResponseFormat> deleteInterfaceOperation(String componentId, - String interfaceId, List operationsToDelete, User user, boolean lock) { + public Either, ResponseFormat> deleteInterfaceOperation(String componentId, String interfaceId, + List operationsToDelete, User user, boolean lock) { validateUserExists(user.getUserId()); - Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - lockComponentResult(lock, storedComponent, DELETE_INTERFACE_OPERATION); - - try { - Optional optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId( - storedComponent, interfaceId); + Optional optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceId); if (!optionalInterface.isPresent()) { - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId)); } InterfaceDefinition interfaceDefinition = optionalInterface.get(); - Map operationsCollection = new HashMap<>(); for (String operationId : operationsToDelete) { - Optional> optionalOperation = - getOperationFromInterfaceDefinition(interfaceDefinition, operationId); + Optional> optionalOperation = getOperationFromInterfaceDefinition(interfaceDefinition, operationId); if (!optionalOperation.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, - storedComponent.getUniqueId())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId())); } - Operation storedOperation = optionalOperation.get().getValue(); - Either validateDeleteOperationContainsNoMappedOutputResponse = - interfaceOperationValidation.validateDeleteOperationContainsNoMappedOutput(storedOperation, - storedComponent, interfaceDefinition); + Either validateDeleteOperationContainsNoMappedOutputResponse = interfaceOperationValidation + .validateDeleteOperationContainsNoMappedOutput(storedOperation, storedComponent, interfaceDefinition); if (validateDeleteOperationContainsNoMappedOutputResponse.isRight()) { return Either.right(validateDeleteOperationContainsNoMappedOutputResponse.right().value()); } - String artifactUniqueId = storedOperation.getImplementation().getUniqueId(); - if(!InterfaceOperationUtils.isArtifactInUse(storedComponent, operationId, artifactUniqueId)){ - Either getArtifactEither = - artifactToscaOperation.getArtifactById(storedComponent.getUniqueId(), artifactUniqueId); - if(getArtifactEither.isLeft()){ - Either removeArifactFromComponent = - artifactToscaOperation.removeArifactFromResource(componentId, artifactUniqueId, - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), - true); - if(removeArifactFromComponent.isRight()){ + if (!InterfaceOperationUtils.isArtifactInUse(storedComponent, operationId, artifactUniqueId)) { + Either getArtifactEither = artifactToscaOperation + .getArtifactById(storedComponent.getUniqueId(), artifactUniqueId); + if (getArtifactEither.isLeft()) { + Either removeArifactFromComponent = artifactToscaOperation + .removeArifactFromResource(componentId, artifactUniqueId, + NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), true); + if (removeArifactFromComponent.isRight()) { janusGraphDao.rollback(); - ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( - componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()), + ResponseFormat responseFormatByArtifactId = componentsUtils + .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()), storedOperation.getImplementation().getArtifactDisplayName()); return Either.right(responseFormatByArtifactId); } - CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUniqueId); if (cassandraStatus != CassandraOperationStatus.OK) { janusGraphDao.rollback(); ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( - componentsUtils.convertFromStorageResponse( - componentsUtils.convertToStorageOperationStatus(cassandraStatus)), - storedOperation.getImplementation().getArtifactDisplayName()); + componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), + storedOperation.getImplementation().getArtifactDisplayName()); return Either.right(responseFormatByArtifactId); } } } - operationsCollection.put(operationId, interfaceDefinition.getOperationsMap().get(operationId)); interfaceDefinition.getOperations().remove(operationId); } - - Either, StorageOperationStatus> deleteOperationEither = - interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), - Collections.singletonList(interfaceDefinition)); + Either, StorageOperationStatus> deleteOperationEither = interfaceOperation + .updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(interfaceDefinition)); if (deleteOperationEither.isRight()) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - deleteOperationEither.right().value(), storedComponent.getComponentType()))); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(deleteOperationEither.right().value(), storedComponent.getComponentType()))); } - if (interfaceDefinition.getOperations().isEmpty()) { - Either deleteInterfaceEither = interfaceOperation.deleteInterface( - storedComponent.getUniqueId(), interfaceDefinition.getUniqueId()); + Either deleteInterfaceEither = interfaceOperation + .deleteInterface(storedComponent.getUniqueId(), interfaceDefinition.getUniqueId()); if (deleteInterfaceEither.isRight()) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - deleteInterfaceEither.right().value(), storedComponent.getComponentType()))); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(deleteInterfaceEither.right().value(), storedComponent.getComponentType()))); } } - janusGraphDao.commit(); interfaceDefinition.getOperations().putAll(operationsCollection); interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToDelete.contains(key))); @@ -207,177 +180,144 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_DELETED)); } finally { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } private Either getComponentDetails(String componentId) { - Either componentStorageOperationStatusEither = - toscaOperationFacade.getToscaElement(componentId); + Either componentStorageOperationStatusEither = toscaOperationFacade + .getToscaElement(componentId); if (componentStorageOperationStatusEither.isRight()) { - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(componentStorageOperationStatusEither.right().value()))); + return Either.right( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentStorageOperationStatusEither.right().value()))); } return Either.left(componentStorageOperationStatusEither.left().value()); } - private Either lockComponentResult(boolean lock, - org.openecomp.sdc.be.model.Component component, String action) { + private Either lockComponentResult(boolean lock, org.openecomp.sdc.be.model.Component component, String action) { if (lock) { try { lockComponent(component.getUniqueId(), component, action); } catch (ComponentException e) { - janusGraphDao.rollback(); - throw e; + janusGraphDao.rollback(); + throw e; + } } - } return Either.left(true); } - public Either, ResponseFormat> getInterfaceOperation(String componentId, - String interfaceId, List operationsToGet, User user, boolean lock) { + public Either, ResponseFormat> getInterfaceOperation(String componentId, String interfaceId, + List operationsToGet, User user, boolean lock) { validateUserExists(user); - Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - lockComponentResult(lock, storedComponent, GET_INTERFACE_OPERATION); - try { - Optional optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId( - storedComponent, interfaceId); + Optional optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceId); if (!optionalInterface.isPresent()) { - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId)); } InterfaceDefinition interfaceDefinition = optionalInterface.get(); - for (String operationId : operationsToGet) { - Optional> optionalOperation = - getOperationFromInterfaceDefinition(interfaceDefinition, operationId); + Optional> optionalOperation = getOperationFromInterfaceDefinition(interfaceDefinition, operationId); if (!optionalOperation.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, - storedComponent.getUniqueId())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId())); } } - janusGraphDao.commit(); interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToGet.contains(key))); return Either.left(Collections.singletonList(interfaceDefinition)); } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e); janusGraphDao.rollback(); - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId)); } finally { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } public Either, ResponseFormat> createInterfaceOperation(String componentId, - List interfaceDefinitions, User user, boolean lock) { - return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, false, - CREATE_INTERFACE_OPERATION, lock); + List interfaceDefinitions, User user, + boolean lock) { + return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, false, CREATE_INTERFACE_OPERATION, lock); } private Either, ResponseFormat> createOrUpdateInterfaceOperation(String componentId, - List interfaceDefinitions, User user, boolean isUpdate, String errorContext, - boolean lock) { + List interfaceDefinitions, + User user, boolean isUpdate, String errorContext, + boolean lock) { validateUserExists(user); - Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - lockComponentResult(lock, storedComponent, errorContext); - - - Either, ResponseFormat> interfaceLifecycleTypes = - getAllInterfaceLifecycleTypes(); + Either, ResponseFormat> interfaceLifecycleTypes = getAllInterfaceLifecycleTypes(); if (interfaceLifecycleTypes.isRight()) { return Either.right(interfaceLifecycleTypes.right().value()); } - try { List interfacesCollection = new ArrayList<>(); Map operationsCollection = new HashMap<>(); for (InterfaceDefinition inputInterfaceDefinition : interfaceDefinitions) { - Optional optionalInterface = - getInterfaceDefinitionFromComponentByInterfaceType( - storedComponent, inputInterfaceDefinition.getType()); - Either interfaceOperationValidationResponseEither = - interfaceOperationValidation - .validateInterfaceOperations(inputInterfaceDefinition, storedComponent, - optionalInterface.orElse(null), interfaceLifecycleTypes.left().value(), - isUpdate); + Optional optionalInterface = getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, + inputInterfaceDefinition.getType()); + Either interfaceOperationValidationResponseEither = interfaceOperationValidation + .validateInterfaceOperations(inputInterfaceDefinition, storedComponent, optionalInterface.orElse(null), + interfaceLifecycleTypes.left().value(), isUpdate); if (interfaceOperationValidationResponseEither.isRight()) { return Either.right(interfaceOperationValidationResponseEither.right().value()); } - Map operationsToAddOrUpdate = inputInterfaceDefinition.getOperationsMap(); operationsCollection.putAll(operationsToAddOrUpdate); inputInterfaceDefinition.getOperations().clear(); - - Either getInterfaceEither = - getOrCreateInterfaceDefinition(storedComponent, inputInterfaceDefinition, - optionalInterface.orElse(null)); + Either getInterfaceEither = getOrCreateInterfaceDefinition(storedComponent, + inputInterfaceDefinition, optionalInterface.orElse(null)); if (getInterfaceEither.isRight()) { return Either.right(getInterfaceEither.right().value()); } InterfaceDefinition interfaceDef = getInterfaceEither.left().value(); - updateOperationInputDefs(storedComponent, operationsToAddOrUpdate.values()); - for (Operation operation : operationsToAddOrUpdate.values()) { if (!isUpdate) { addOperationToInterface(interfaceDef, operation); } else { - Optional> optionalOperation = - getOperationFromInterfaceDefinition(interfaceDef, - operation.getUniqueId()); + Optional> optionalOperation = getOperationFromInterfaceDefinition(interfaceDef, + operation.getUniqueId()); if (!optionalOperation.isPresent()) { janusGraphDao.rollback(); - return Either.right(componentsUtils - .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, - storedComponent.getUniqueId())); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId())); } - Operation storedOperation = optionalOperation.get().getValue(); String artifactUuId = storedOperation.getImplementation().getArtifactUUID(); String artifactUniqueId = storedOperation.getImplementation().getUniqueId(); - - if(!InterfaceOperationUtils.isArtifactInUse(storedComponent, storedOperation.getUniqueId(), artifactUniqueId)){ - Either getArtifactEither = - artifactToscaOperation.getArtifactById(storedComponent.getUniqueId(), artifactUniqueId); - if(getArtifactEither.isLeft()){ - Either removeArifactFromComponent = - artifactToscaOperation.removeArifactFromResource(componentId, artifactUniqueId, - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), - true); - if(removeArifactFromComponent.isRight()){ + if (!InterfaceOperationUtils.isArtifactInUse(storedComponent, storedOperation.getUniqueId(), artifactUniqueId)) { + Either getArtifactEither = artifactToscaOperation + .getArtifactById(storedComponent.getUniqueId(), artifactUniqueId); + if (getArtifactEither.isLeft()) { + Either removeArifactFromComponent = artifactToscaOperation + .removeArifactFromResource(componentId, artifactUniqueId, + NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), true); + if (removeArifactFromComponent.isRight()) { janusGraphDao.rollback(); ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( - componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()), - storedOperation.getImplementation().getArtifactDisplayName()); + componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()), + storedOperation.getImplementation().getArtifactDisplayName()); return Either.right(responseFormatByArtifactId); } - CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUniqueId); if (cassandraStatus != CassandraOperationStatus.OK) { janusGraphDao.rollback(); - ResponseFormat responseFormatByArtifactId = - componentsUtils.getResponseFormatByArtifactId( - componentsUtils.convertFromStorageResponse( - componentsUtils.convertToStorageOperationStatus( - cassandraStatus)), - storedOperation.getImplementation().getArtifactDisplayName()); + ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( + componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), + storedOperation.getImplementation().getArtifactDisplayName()); return Either.right(responseFormatByArtifactId); } } @@ -387,73 +327,64 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } interfacesCollection.add(interfaceDef); } - - Either, StorageOperationStatus> addCreateOperationEither = - interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), interfacesCollection); + Either, StorageOperationStatus> addCreateOperationEither = interfaceOperation + .updateInterfaces(storedComponent.getUniqueId(), interfacesCollection); if (addCreateOperationEither.isRight()) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - addCreateOperationEither.right().value(), storedComponent.getComponentType()))); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(addCreateOperationEither.right().value(), storedComponent.getComponentType()))); } - janusGraphDao.commit(); interfacesCollection.forEach(interfaceDefinition -> interfaceDefinition.getOperations().entrySet().removeIf( - entry -> !operationsCollection.values().stream().map(OperationDataDefinition::getName) - .collect(Collectors.toList()).contains(entry.getValue().getName()))); + entry -> !operationsCollection.values().stream().map(OperationDataDefinition::getName).collect(Collectors.toList()) + .contains(entry.getValue().getName()))); return Either.left(interfacesCollection); } catch (Exception e) { janusGraphDao.rollback(); LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "addOrUpdate", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } public Either, ResponseFormat> getAllInterfaceLifecycleTypes() { - - Either, StorageOperationStatus> interfaceLifecycleTypes = - interfaceLifecycleTypeOperation.getAllInterfaceLifecycleTypes(); + Either, StorageOperationStatus> interfaceLifecycleTypes = interfaceLifecycleTypeOperation + .getAllInterfaceLifecycleTypes(); if (interfaceLifecycleTypes.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_LIFECYCLE_TYPES_NOT_FOUND)); } - interfaceLifecycleTypes.left().value().values().forEach(id -> id.setOperations( - id.getOperations().keySet().stream().collect(Collectors.toMap(key -> key.replaceFirst( - id.getUniqueId() + ".", ""), i -> id.getOperations().get(i))))); - + interfaceLifecycleTypes.left().value().values().forEach(id -> id.setOperations(id.getOperations().keySet().stream() + .collect(Collectors.toMap(key -> key.replaceFirst(id.getUniqueId() + ".", ""), i -> id.getOperations().get(i))))); return Either.left(interfaceLifecycleTypes.left().value()); } - private Either getOrCreateInterfaceDefinition( - org.openecomp.sdc.be.model.Component component, InterfaceDefinition interfaceDefinition, - InterfaceDefinition storedInterfaceDef) { + private Either getOrCreateInterfaceDefinition(org.openecomp.sdc.be.model.Component component, + InterfaceDefinition interfaceDefinition, + InterfaceDefinition storedInterfaceDef) { if (storedInterfaceDef != null) { return Either.left(storedInterfaceDef); } interfaceDefinition.setUniqueId(UUID.randomUUID().toString()); interfaceDefinition.setToscaResourceName(interfaceDefinition.getType()); - Either, StorageOperationStatus> interfaceCreateEither = - interfaceOperation.addInterfaces(component.getUniqueId(), - Collections.singletonList(interfaceDefinition)); + Either, StorageOperationStatus> interfaceCreateEither = interfaceOperation + .addInterfaces(component.getUniqueId(), Collections.singletonList(interfaceDefinition)); if (interfaceCreateEither.isRight()) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - interfaceCreateEither.right().value(), component.getComponentType()))); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(interfaceCreateEither.right().value(), component.getComponentType()))); } return Either.left(interfaceCreateEither.left().value().get(0)); } - private void updateOperationInputDefs(org.openecomp.sdc.be.model.Component component, - Collection interfaceOperations) { + private void updateOperationInputDefs(org.openecomp.sdc.be.model.Component component, Collection interfaceOperations) { interfaceOperations.stream().filter(operation -> Objects.nonNull(operation.getInputs())).forEach( - operation -> operation.getInputs().getListToscaDataDefinition().forEach( - inp -> component.getInputs() - .forEach(in -> updateOperationInputDefinition(component, inp, in)))); + operation -> operation.getInputs().getListToscaDataDefinition() + .forEach(inp -> component.getInputs().forEach(in -> updateOperationInputDefinition(component, inp, in)))); } - private void updateOperationInputDefinition(org.openecomp.sdc.be.model.Component component, - OperationInputDefinition operationInput, + private void updateOperationInputDefinition(org.openecomp.sdc.be.model.Component component, OperationInputDefinition operationInput, InputDefinition componentInput) { if (operationInput.getInputId().equals(componentInput.getUniqueId())) { //Set the default value, value and schema only for inputs mapped to component inputs @@ -461,41 +392,32 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { operationInput.setToscaDefaultValue(getInputToscaDefaultValue(operationInput, component)); operationInput.setValue(componentInput.getValue()); operationInput.setSchema(componentInput.getSchema()); - operationInput.setParentPropertyType(componentInput.getParentPropertyType()); - operationInput.setSubPropertyInputPath(componentInput.getSubPropertyInputPath()); + operationInput.setParentPropertyType(componentInput.getParentPropertyType()); + operationInput.setSubPropertyInputPath(componentInput.getSubPropertyInputPath()); } //Set the tosca default value for inputs mapped to component inputs as well as other outputs operationInput.setToscaDefaultValue(getInputToscaDefaultValue(operationInput, component)); } - private String getInputToscaDefaultValue(OperationInputDefinition input, - org.openecomp.sdc.be.model.Component component) { + private String getInputToscaDefaultValue(OperationInputDefinition input, org.openecomp.sdc.be.model.Component component) { Map> defaultInputValue = null; if (isOperationInputMappedToComponentInput(input, component.getInputs())) { String propertyName = input.getInputId().substring(input.getInputId().indexOf('.') + 1); - setParentPropertyTypeAndInputPath(input, component); + setParentPropertyTypeAndInputPath(input, component); defaultInputValue = createMappedInputPropertyDefaultValue(propertyName); } else if (isCapabilityProperty(input.getInputId(), component).isPresent()) { - Optional instancePropertyOpt = isCapabilityProperty(input.getInputId(), - component); + Optional instancePropertyOpt = isCapabilityProperty(input.getInputId(), component); Optional parentPropertyIdOpt = instancePropertyOpt.map(PropertyDataDefinition::getParentUniqueId); Map> componentCapabilities = component.getCapabilities(); - if(MapUtils.isNotEmpty(componentCapabilities)) { - List capabilityDefinitionList = componentCapabilities.values().stream() - .flatMap(Collection::stream) - .filter(capabilityDefinition -> capabilityDefinition.getOwnerId().equals(component.getUniqueId())) - .collect(Collectors.toList()); - + if (MapUtils.isNotEmpty(componentCapabilities)) { + List capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream) + .filter(capabilityDefinition -> capabilityDefinition.getOwnerId().equals(component.getUniqueId())).collect(Collectors.toList()); defaultInputValue = parentPropertyIdOpt - .flatMap(parentPropertyId -> - getPropertyCapabilityFromAllCapProps(parentPropertyId, capabilityDefinitionList)) - .flatMap(capability -> - instancePropertyOpt.map(instanceProperty -> - new ImmutablePair<>(capability.getName(), instanceProperty.getName()))) - .map(tuple -> { + .flatMap(parentPropertyId -> getPropertyCapabilityFromAllCapProps(parentPropertyId, capabilityDefinitionList)).flatMap( + capability -> instancePropertyOpt + .map(instanceProperty -> new ImmutablePair<>(capability.getName(), instanceProperty.getName()))).map(tuple -> { String propertyName = tuple.right; String capabilityName = tuple.left; - return createMappedCapabilityPropertyDefaultValue(capabilityName, propertyName); }).orElse(null); } @@ -506,36 +428,28 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { return new Gson().toJson(defaultInputValue); } - private void setParentPropertyTypeAndInputPath(OperationInputDefinition input, - org.openecomp.sdc.be.model.Component component) { - if (CollectionUtils.isEmpty(component.getInputs())) { - return; - } - - component.getInputs() - .stream() - .filter(inp -> inp.getUniqueId().equals( - input.getInputId().substring(0, input.getInputId().lastIndexOf('.')))) - .forEach(inp -> { - input.setParentPropertyType(inp.getParentPropertyType()); - if (Objects.nonNull(input.getName())) { - input.setSubPropertyInputPath(input.getName().replaceAll("\\.", "#")); - } - }); - } + private void setParentPropertyTypeAndInputPath(OperationInputDefinition input, org.openecomp.sdc.be.model.Component component) { + if (CollectionUtils.isEmpty(component.getInputs())) { + return; + } + component.getInputs().stream().filter(inp -> inp.getUniqueId().equals(input.getInputId().substring(0, input.getInputId().lastIndexOf('.')))) + .forEach(inp -> { + input.setParentPropertyType(inp.getParentPropertyType()); + if (Objects.nonNull(input.getName())) { + input.setSubPropertyInputPath(input.getName().replaceAll("\\.", "#")); + } + }); + } private void addOperationToInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation) { interfaceOperation.setUniqueId(UUID.randomUUID().toString()); interfaceOperation.setImplementation(createArtifactDefinition(UUID.randomUUID().toString(), interfaceOperation)); - interfaceDefinition.getOperations() - .put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation)); + interfaceDefinition.getOperations().put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation)); } - private void updateOperationOnInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation, - String artifactUuId) { + private void updateOperationOnInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation, String artifactUuId) { interfaceOperation.setImplementation(createArtifactDefinition(artifactUuId, interfaceOperation)); - interfaceDefinition.getOperations() - .put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation)); + interfaceDefinition.getOperations().put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation)); } private ArtifactDefinition createArtifactDefinition(String artifactUuId, Operation operation) { @@ -551,60 +465,50 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } public Either, ResponseFormat> updateInterfaceOperation(String componentId, - List interfaceDefinitions, User user, boolean lock) { - return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, true, - UPDATE_INTERFACE_OPERATION, lock); + List interfaceDefinitions, User user, + boolean lock) { + return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, true, UPDATE_INTERFACE_OPERATION, lock); } - public Either, ResponseFormat> getInputsListForOperation(String componentId, - String componentInstanceId, String interfaceId, String operationId, User user) { + public Either, ResponseFormat> getInputsListForOperation(String componentId, String componentInstanceId, + String interfaceId, String operationId, User user) { Either componentEither = getComponentDetails(componentId); - if (componentEither.isRight()){ + if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } - org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); validateUserExists(user.getUserId()); - Either lockResult = lockComponentResult(true, storedComponent, GET_INTERFACE_OPERATION); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } - - try{ + try { org.openecomp.sdc.be.model.Component parentComponent = componentEither.left().value(); - Map> componentInstanceInterfaces = - parentComponent.getComponentInstancesInterfaces(); - if(MapUtils.isEmpty(componentInstanceInterfaces)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, - componentInstanceId)); + Map> componentInstanceInterfaces = parentComponent.getComponentInstancesInterfaces(); + if (MapUtils.isEmpty(componentInstanceInterfaces)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentInstanceId)); } - - List componentInstanceInterfaceList = - componentInstanceInterfaces.get(componentInstanceId); - for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaceList) { - if(componentInstanceInterface.getInterfaceId().equals(interfaceId)){ + List componentInstanceInterfaceList = componentInstanceInterfaces.get(componentInstanceId); + for (ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaceList) { + if (componentInstanceInterface.getInterfaceId().equals(interfaceId)) { Map operations = componentInstanceInterface.getOperations(); - if(MapUtils.isNotEmpty(operations) && operations.containsKey(operationId)) { + if (MapUtils.isNotEmpty(operations) && operations.containsKey(operationId)) { ListDataDefinition inputs = operations.get(operationId).getInputs(); - return Either.left(CollectionUtils.isEmpty(inputs.getListToscaDataDefinition()) - ? new ArrayList<>() : inputs.getListToscaDataDefinition()); + return Either.left( + CollectionUtils.isEmpty(inputs.getListToscaDataDefinition()) ? new ArrayList<>() : inputs.getListToscaDataDefinition()); } } } return Either.left(new ArrayList<>()); - } - catch (Exception e) { + } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e); janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND)); - } - finally { + } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java index 927c8b17b7..9d72eeca87 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java @@ -13,20 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.impl; -import org.onap.sdc.tosca.services.YamlUtil; -import org.openecomp.sdc.be.model.UploadNodeFilterCapabilitiesInfo; -import org.openecomp.sdc.be.model.UploadNodeFilterInfo; -import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo; -import org.openecomp.sdc.be.utils.TypeUtils; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import org.onap.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.be.model.UploadNodeFilterCapabilitiesInfo; +import org.openecomp.sdc.be.model.UploadNodeFilterInfo; +import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo; +import org.openecomp.sdc.be.utils.TypeUtils; public class NodeFilterUploadCreator { @@ -35,7 +33,6 @@ public class NodeFilterUploadCreator { return null; } Map nodeFilterMap = (Map) obj; - UploadNodeFilterInfo uploadNodeFilterInfo = new UploadNodeFilterInfo(); final String propertiesElementName = TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName(); if (nodeFilterMap.containsKey(propertiesElementName)) { @@ -43,8 +40,7 @@ public class NodeFilterUploadCreator { } final String capabilitiesElementName = TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName(); if (nodeFilterMap.containsKey(capabilitiesElementName)) { - uploadNodeFilterInfo - .setCapabilities(createNodeFilterCapabilities(nodeFilterMap.get(capabilitiesElementName))); + uploadNodeFilterInfo.setCapabilities(createNodeFilterCapabilities(nodeFilterMap.get(capabilitiesElementName))); } final String toscaId = TypeUtils.ToscaTagNamesEnum.TOSCA_ID.getElementName(); if (nodeFilterMap.containsKey(toscaId)) { @@ -67,8 +63,7 @@ public class NodeFilterUploadCreator { valueList.add(valueToProperty(entry.getValue())); retVal.add(new UploadNodeFilterPropertyInfo(entry.getKey(), valueList)); } else if (value instanceof List) { - List propertiesVals = - (List) ((List) value).stream().map(this::valueToProperty).collect(Collectors.toList()); + List propertiesVals = (List) ((List) value).stream().map(this::valueToProperty).collect(Collectors.toList()); retVal.add(new UploadNodeFilterPropertyInfo(entry.getKey(), propertiesVals)); } } @@ -76,7 +71,6 @@ public class NodeFilterUploadCreator { } private String valueToProperty(Object o) { - if (o instanceof Map) { return new YamlUtil().objectToYaml(o); } @@ -97,7 +91,6 @@ public class NodeFilterUploadCreator { retVal.put(entry.getKey(), uploadNodeFilterCapabilitiesInfo); } return retVal; - } private List createCapabilitiesProperties(Object o) { @@ -112,6 +105,4 @@ public class NodeFilterUploadCreator { } return null; } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java index f64c11a077..2a9157ac14 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -27,10 +26,10 @@ public interface OnDeleteEntityOperation { /** * side effect operation to be executed when a given entity is deleted - * @param container the container which holds the entity to be deleted + * + * @param container the container which holds the entity to be deleted * @param deletedEntityId the id of the entity that was deleted * @return the status of the on delete operation */ ActionStatus onDelete(Component container, String deletedEntityId); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java index cfb6004620..2d6a619cc7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; @@ -57,7 +56,6 @@ import org.springframework.beans.factory.annotation.Autowired; public class OutputsBusinessLogic extends BaseBusinessLogic { private static final String CREATE_OUTPUT = "CreateOutput"; - private static final Logger log = Logger.getLogger(OutputsBusinessLogic.class); private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}"; private static final String GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP = "Going to execute rollback on create group."; @@ -65,16 +63,12 @@ public class OutputsBusinessLogic extends BaseBusinessLogic { private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(OutputsBusinessLogic.class); private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID = "Failed to found component instance outputs componentInstanceId: {}"; private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR = "Failed to found component instance outputs {}, error: {}"; - private final AttributeDeclarationOrchestrator attributeDeclarationOrchestrator; @Autowired - public OutputsBusinessLogic(final IElementOperation elementDao, - final IGroupOperation groupOperation, - final IGroupInstanceOperation groupInstanceOperation, - final IGroupTypeOperation groupTypeOperation, - final InterfaceOperation interfaceOperation, - final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + public OutputsBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation, + final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation, + final InterfaceOperation interfaceOperation, final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, final AttributeDeclarationOrchestrator attributeDeclarationOrchestrator, final ArtifactsOperations artifactToscaOperation) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, @@ -82,76 +76,58 @@ public class OutputsBusinessLogic extends BaseBusinessLogic { this.attributeDeclarationOrchestrator = attributeDeclarationOrchestrator; } - public Either, ResponseFormat> getComponentInstanceOutputs(final String userId, - final String componentId, + public Either, ResponseFormat> getComponentInstanceOutputs(final String userId, final String componentId, final String componentInstanceId) { - validateUserExists(userId); final ComponentParametersView filters = new ComponentParametersView(); filters.disableAll(); filters.setIgnoreOutputs(false); filters.setIgnoreComponentInstances(false); filters.setIgnoreComponentInstancesOutputs(false); - final Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ + 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)); - } final Component component = getComponentEither.left().value(); - if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) { final ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; log.debug(FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR, componentInstanceId, actionStatus); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), - StatusCode.ERROR, FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID, componentInstanceId); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), StatusCode.ERROR, + FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID, componentInstanceId); return Either.right(componentsUtils.getResponseFormat(actionStatus)); } final Map> ciOutputs = Optional.ofNullable(component.getComponentInstancesOutputs()) .orElse(Collections.emptyMap()); - return Either.left(ciOutputs.getOrDefault(componentInstanceId, Collections.emptyList())); } @Override - public Either, ResponseFormat> declareAttributes(final String userId, - final String componentId, + public Either, ResponseFormat> declareAttributes(final String userId, final String componentId, final ComponentTypeEnum componentTypeEnum, final ComponentInstOutputsMap componentInstOutputsMap) { - return createMultipleOutputs(userId, componentId, componentTypeEnum, componentInstOutputsMap, true, false); } - public Either, ResponseFormat> createMultipleOutputs(final String userId, - final String componentId, + public Either, ResponseFormat> createMultipleOutputs(final String userId, final String componentId, final ComponentTypeEnum componentType, final ComponentInstOutputsMap componentInstOutputsMapUi, - final boolean shouldLockComp, - final boolean inTransaction) { - + final boolean shouldLockComp, final boolean inTransaction) { Either, ResponseFormat> result = null; org.openecomp.sdc.be.model.Component component = null; - try { validateUserExists(userId); - component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp); - - result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi) - .left() - .bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate)) - .right() + result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi).left() + .bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate)).right() .map(componentsUtils::getResponseFormat); return result; - } catch (final ByResponseFormatComponentException e) { log.error("#createMultipleOutputs: Exception thrown: ", e); result = Either.right(e.getResponseFormat()); return result; } finally { - if (!inTransaction) { if (result == null || result.isRight()) { log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP); @@ -165,12 +141,10 @@ public class OutputsBusinessLogic extends BaseBusinessLogic { if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - } } - private org.openecomp.sdc.be.model.Component getAndValidateComponentForCreate(final String userId, - final String componentId, + private org.openecomp.sdc.be.model.Component getAndValidateComponentForCreate(final String userId, final String componentId, final ComponentTypeEnum componentType, final boolean shouldLockComp) { final ComponentParametersView componentParametersView = getBaseComponentParametersView(); @@ -183,15 +157,11 @@ public class OutputsBusinessLogic extends BaseBusinessLogic { return component; } - private Either, StorageOperationStatus> prepareOutputsForCreation(final String userId, - final String cmptId, + private Either, StorageOperationStatus> prepareOutputsForCreation(final String userId, final String cmptId, final List outputsToCreate) { final Map outputsToPersist = MapUtil.toMap(outputsToCreate, OutputDefinition::getName); assignOwnerIdToOutputs(userId, outputsToPersist); - - return toscaOperationFacade.addOutputsToComponent(outputsToPersist, cmptId) - .left() - .map(persistedOutputs -> outputsToCreate); + return toscaOperationFacade.addOutputsToComponent(outputsToPersist, cmptId).left().map(persistedOutputs -> outputsToCreate); } private void assignOwnerIdToOutputs(final String userId, final Map outputsToCreate) { @@ -219,24 +189,19 @@ public class OutputsBusinessLogic extends BaseBusinessLogic { * @return */ public OutputDefinition deleteOutput(final String componentId, final String userId, final String outputId) { - Either deleteEither = null; if (log.isDebugEnabled()) { log.debug("Going to delete output id: {}", outputId); } - validateUserExists(userId); - final ComponentParametersView componentParametersView = getBaseComponentParametersView(); componentParametersView.setIgnoreAttributes(false); - - final Either componentEither = - toscaOperationFacade.getToscaElement(componentId, componentParametersView); + final Either componentEither = toscaOperationFacade + .getToscaElement(componentId, componentParametersView); if (componentEither.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value())); } final org.openecomp.sdc.be.model.Component component = componentEither.left().value(); - // Validate outputId is child of the component final Optional optionalOutput = component.getOutputs().stream(). // filter by ID @@ -246,23 +211,19 @@ public class OutputsBusinessLogic extends BaseBusinessLogic { if (!optionalOutput.isPresent()) { throw new ByActionStatusComponentException(ActionStatus.OUTPUT_IS_NOT_CHILD_OF_COMPONENT, outputId, componentId); } - final OutputDefinition outputForDelete = optionalOutput.get(); - // Lock component lockComponent(componentId, component, "deleteOutput"); // Delete output operations boolean failed = false; try { - final StorageOperationStatus status = - toscaOperationFacade.deleteOutputOfResource(component, outputForDelete.getName()); + final StorageOperationStatus status = toscaOperationFacade.deleteOutputOfResource(component, outputForDelete.getName()); if (status != StorageOperationStatus.OK) { log.debug("Component id: {} delete output id: {} failed", componentId, outputId); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName()); } - - final StorageOperationStatus storageOperationStatus = - attributeDeclarationOrchestrator.unDeclareAttributesAsOutputs(component, outputForDelete); + final StorageOperationStatus storageOperationStatus = attributeDeclarationOrchestrator + .unDeclareAttributesAsOutputs(component, outputForDelete); if (storageOperationStatus != StorageOperationStatus.OK) { log.debug("Component id: {} update attributes declared as output for outputId: {} failed", componentId, outputId); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName()); @@ -275,5 +236,4 @@ public class OutputsBusinessLogic extends BaseBusinessLogic { unlockComponent(failed, component); } } - } 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 index f872074f26..70e387915d 100644 --- 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 @@ -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. @@ -17,13 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 fj.data.Either; 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.function.Function; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -62,20 +74,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -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; - /** * Provides specified business logic to create, retrieve, update, delete a policy */ @@ -85,20 +83,15 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. "; private static final String DECLARE_PROPERTIES_TO_POLICIES = "declare properties to policies"; private static final Logger log = Logger.getLogger(PolicyBusinessLogic.class); - private static final LoggerSupportability loggerSupportability= LoggerSupportability.getLogger(PolicyBusinessLogic.class.getName()); - + private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(PolicyBusinessLogic.class.getName()); private PropertyDeclarationOrchestrator propertyDeclarationOrchestrator; @Autowired - public PolicyBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public PolicyBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); } @Autowired @@ -116,25 +109,24 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @param shouldLock the flag defining if the component should be locked * @return a policy or an error in a response format */ - - public PolicyDefinition createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) { - + public PolicyDefinition createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, + boolean shouldLock) { log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId); Component component = null; boolean failed = false; try { component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); return createPolicy(policyTypeName, component); - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { unlockComponent(shouldLock, failed, component); } } public Map createPoliciesFromParsedCsar(Component component, - final Map incomingPolicyDefinitions) { + final Map incomingPolicyDefinitions) { if (MapUtils.isEmpty(incomingPolicyDefinitions)) { return Collections.emptyMap(); } @@ -143,8 +135,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { PolicyDefinition incomingPolicyDefinition = policyEntry.getValue(); String policyName = incomingPolicyDefinition.getName(); log.trace("Going to create policy {}", incomingPolicyDefinition); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), - StatusCode.STARTED,"Start to create policy: {} for component {}", policyName, component.getName()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Start to create policy: {} for component {}", policyName, component.getName()); String policyType = incomingPolicyDefinition.getType(); if (StringUtils.isEmpty(policyType)) { log.debug("Policy type '{}' for policy '{}' not found.", policyType, policyName); @@ -164,26 +157,25 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { List properties = incomingPolicyDefinition.getProperties(); createdPolicyDefinition = setUpdatePolicyProperties(component, createdPolicyDefinition, properties); createdPolicies.put(policyName, createdPolicyDefinition); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"policy {} has been created ", policyName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES, component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "policy {} has been created ", policyName); } return createdPolicies; } - private PolicyDefinition setUpdatePolicyProperties(Component component, PolicyDefinition policyDefinition, List properties) { + private PolicyDefinition setUpdatePolicyProperties(Component component, PolicyDefinition policyDefinition, + List properties) { if (CollectionUtils.isNotEmpty(properties)) { PropertyDataDefinition[] propertiesArray = properties.toArray(new PropertyDataDefinition[properties.size()]); - List updatedPropertiesList = setComponentValidateUpdatePolicyProperties( - policyDefinition.getUniqueId(), - propertiesArray, - component - ); + List updatedPropertiesList = setComponentValidateUpdatePolicyProperties(policyDefinition.getUniqueId(), + propertiesArray, component); policyDefinition.setProperties(updatedPropertiesList); } return policyDefinition; } private PolicyDefinition setUpdatePolicyTargets(Component component, PolicyDefinition policyDefinition, - Map> targets) { + Map> targets) { if (MapUtils.isEmpty(targets)) { return policyDefinition; } @@ -196,19 +188,13 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { for (String targetName : targetsToUpdate) { Optional componentInstance = component.getComponentInstanceByName(targetName); String componentUniqueId = componentInstance - .orElseThrow( - () -> new ByActionStatusComponentException( - ActionStatus.COMPONENT_INSTANCE_NOT_FOUND - ) - ) - .getUniqueId(); + .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND)).getUniqueId(); targetsUniqueIds.add(componentUniqueId); } EnumMap> updatedTargets = new EnumMap<>(PolicyTargetType.class); updatedTargets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsUniqueIds); policyDefinition.setTargets(updatedTargets); - policyDefinition = validateAndUpdatePolicyTargets(component, policyDefinition.getUniqueId(), - policyDefinition.getTargets()); + policyDefinition = validateAndUpdatePolicyTargets(component, policyDefinition.getUniqueId(), policyDefinition.getTargets()); return policyDefinition; } @@ -236,7 +222,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } return result; }*/ - public Either, ResponseFormat> getPoliciesList(ComponentTypeEnum componentType, String componentId, String userId) { Either, ResponseFormat> result; log.trace("#getPolicies - starting to retrieve policies of component {}. ", componentId); @@ -250,8 +235,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return result; } - - /** * Retrieves the policy of the component by UniqueId * @@ -266,7 +249,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId); return getPolicyById(component, policyId); } - /*public Either getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { Either result; log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId); @@ -291,7 +273,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @param shouldLock the flag defining if the component should be locked * @return a policy or an error in a response format */ - public PolicyDefinition updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) { + public PolicyDefinition updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, + boolean shouldLock) { Component component = null; boolean failed = false; log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId); @@ -300,15 +283,14 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return validateAndUpdatePolicy(component, policy); } catch (ComponentException e) { failed = true; - log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e); + log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), + componentId, e); throw e; } finally { //TODO Andrey result = boolean unlockComponent(shouldLock, failed, component); } } - - /*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); @@ -344,20 +326,20 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { PolicyDefinition result = null; log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId); Component component = null; - boolean failed= false; + boolean failed = false; try { component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); return deletePolicy(component, policyId); } catch (ComponentException e) { failed = true; - log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e); + log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, + e); throw e; } finally { unlockComponent(shouldLock, failed, component); } } - /*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); @@ -409,39 +391,35 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { unlockComponent(shouldLock, result, component); } }*/ - - public Either undeclarePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) { + public Either undeclarePolicy(ComponentTypeEnum componentType, String componentId, String policyId, + String userId, boolean shouldLock) { Either result = null; log.trace("#undeclarePolicy - starting to undeclare policy {} on component {}. ", policyId, componentId); Wrapper component = new Wrapper<>(); try { validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); - ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreComponentInstances(false); componentParametersView.setIgnoreComponentInstancesProperties(false); componentParametersView.setIgnorePolicies(false); - - Either componentWithFilters = - toscaOperationFacade.getToscaElement(componentId, componentParametersView); + Either componentWithFilters = toscaOperationFacade + .getToscaElement(componentId, componentParametersView); if (componentWithFilters.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentWithFilters.right().value()))); + return Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentWithFilters.right().value()))); } - Component containerComponent = componentWithFilters.left().value(); - Optional policyCandidate = getPolicyForUndeclaration(policyId, containerComponent); - if(policyCandidate.isPresent()) { + if (policyCandidate.isPresent()) { result = undeclarePolicy(policyCandidate.get(), containerComponent); } - return result; - }catch (Exception e) { + } catch (Exception e) { log.error("#undeclarePolicy - the exception occurred upon update of a policy of type {} for component {}: ", policyId, componentId, e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, e.getMessage())); } finally { - if (result == null || result.isRight()){ + if (result == null || result.isRight()) { unlockComponent(shouldLock, true, component); } else { unlockComponent(shouldLock, false, component); @@ -449,56 +427,45 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } } - private Either undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) { - StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator - .unDeclarePropertiesAsPolicies(containerComponent, policyDefinition); - if(undeclareStatus != StorageOperationStatus.OK){ - return Either.right(componentsUtils.getResponseFormat(undeclareStatus)); - } else { - return Either.left(policyDefinition); - } + private Either undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) { + StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsPolicies(containerComponent, policyDefinition); + if (undeclareStatus != StorageOperationStatus.OK) { + return Either.right(componentsUtils.getResponseFormat(undeclareStatus)); + } else { + return Either.left(policyDefinition); } + } - - private Optional getPolicyForUndeclaration(String policyId, Component component) { - Map policies = component.getPolicies(); - if(MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) { - return Optional.of(policies.get(policyId)); - } - - Map> componentInstancesProperties = - MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties(); - - for(Map.Entry> instancePropertyEntry : componentInstancesProperties.entrySet()) { - Optional propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue()); - - if(propertyCandidate.isPresent()) { - return Optional.of( - PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get())); - } + private Optional getPolicyForUndeclaration(String policyId, Component component) { + Map policies = component.getPolicies(); + if (MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) { + return Optional.of(policies.get(policyId)); + } + Map> componentInstancesProperties = + MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties(); + for (Map.Entry> instancePropertyEntry : componentInstancesProperties.entrySet()) { + Optional propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue()); + if (propertyCandidate.isPresent()) { + return Optional.of(PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get())); } - - return Optional.empty(); } + return Optional.empty(); + } - private Optional getPropertyForDeclaredPolicy(String policyId, List componentInstanceProperties) { - for(ComponentInstanceProperty property : componentInstanceProperties) { - Optional getPolicyCandidate = property.safeGetGetPolicyValues().stream() - .filter(getPolicyValue -> getPolicyValue.getPolicyId() - .equals(policyId)) - .findAny(); - - if(getPolicyCandidate.isPresent()) { - return Optional.of(property); - } + private Optional getPropertyForDeclaredPolicy(String policyId, + List componentInstanceProperties) { + for (ComponentInstanceProperty property : componentInstanceProperties) { + Optional getPolicyCandidate = property.safeGetGetPolicyValues().stream() + .filter(getPolicyValue -> getPolicyValue.getPolicyId().equals(policyId)).findAny(); + if (getPolicyCandidate.isPresent()) { + return Optional.of(property); } - - return Optional.empty(); } + return Optional.empty(); + } - - public PolicyDefinition updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map> targets, String userId) { - + public PolicyDefinition 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); boolean failed = false; @@ -506,10 +473,10 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { //not right error response Component component = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true); return validateAndUpdatePolicyTargets(component, policyId, targets); - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { unlockComponentById(failed, componentId); } } @@ -528,7 +495,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return validateTargetExists(parentComponent, targets.entrySet()); } - private Component validateTargetExists(Component parentComponent, Set>> entries) { for (Map.Entry> entry : entries) { checkTargetNotExistOnComponentByType(parentComponent, entry); @@ -537,7 +503,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } private Component checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry> targetEntry) { - for (String id : targetEntry.getValue()) { if (checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().getName())) { throw new ByActionStatusComponentException(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, id); @@ -560,7 +525,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return policyDefinition; } - /** * @param componentType the type of the component * @param componentId the id of the component which the policy resides under @@ -577,7 +541,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { janusGraphDao.commit(); } } - /*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 { @@ -600,7 +563,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { * @param shouldLock the flag defining if the component should be locked * @return a list of policy properties or anerrorin a response format */ - public List updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) { + public List updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, + PropertyDataDefinition[] properties, String userId, boolean shouldLock) { List result; Component component = null; log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId); @@ -618,47 +582,39 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } @Override - public Either, ResponseFormat> declareProperties(String userId, String componentId, - ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) { + public Either, ResponseFormat> declareProperties(String userId, String componentId, ComponentTypeEnum componentTypeEnum, + ComponentInstInputsMap componentInstInputsMap) { return declarePropertiesToPolicies(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); - } private Either, ResponseFormat> declarePropertiesToPolicies(String userId, String componentId, - ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap, boolean shouldLock, - boolean inTransaction) { + ComponentTypeEnum componentTypeEnum, + ComponentInstInputsMap componentInstInputsMap, + boolean shouldLock, boolean inTransaction) { Either, ResponseFormat> result = null; org.openecomp.sdc.be.model.Component component = null; - try { validateUserExists(userId); - ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreComponentInstances(false); componentParametersView.setIgnoreComponentInstancesProperties(false); componentParametersView.setIgnorePolicies(false); componentParametersView.setIgnoreUsers(false); - component = validateComponentExists(componentId, componentTypeEnum, componentParametersView); - if (shouldLock) { lockComponent(component, DECLARE_PROPERTIES_TO_POLICIES); } - validateCanWorkOnComponent(component, userId); - - Either, StorageOperationStatus> declarePropertiesEither = - propertyDeclarationOrchestrator.declarePropertiesToPolicies(component, componentInstInputsMap); - - if(declarePropertiesEither.isRight()) { + Either, StorageOperationStatus> declarePropertiesEither = propertyDeclarationOrchestrator + .declarePropertiesToPolicies(component, componentInstInputsMap); + if (declarePropertiesEither.isRight()) { return Either.right(componentsUtils.getResponseFormat(declarePropertiesEither.right().value())); } - result = Either.left(declarePropertiesEither.left().value()); return result; } finally { - if(!inTransaction) { + if (!inTransaction) { commitOrRollback(result); } // unlock resource @@ -668,9 +624,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } } - private List setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Component component) { + private List setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, + Component component) { Set updatedPropertyNames = Arrays.stream(properties).map(PropertyDataDefinition::getName).collect(Collectors.toSet()); - PolicyDefinition policyDefinition = validateAndUpdatePolicyProperties(component, policyId, properties); return getFilteredProperties(policyDefinition.getProperties(), updatedPropertyNames); } @@ -685,7 +641,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } } - private void unlockComponent(boolean shouldLock, boolean result, Wrapper component) { if (shouldLock && !component.isEmpty()) { unlockComponent(result, component.getInnerElement()); @@ -710,11 +665,10 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { /*private Either createPolicy(String policyTypeName, Component component) { return validatePolicyTypeOnCreatePolicy(policyTypeName, component).left().bind(type -> addPolicyToComponent(type, component)); }*/ - private PolicyDefinition addPolicyToComponent(PolicyTypeDefinition policyType, Component component) { - Either associatePolicyToComponent = - toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies())); - if(associatePolicyToComponent.isRight()){ + Either associatePolicyToComponent = toscaOperationFacade + .associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies())); + if (associatePolicyToComponent.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(associatePolicyToComponent.right().value())); } return associatePolicyToComponent.left().value(); @@ -724,10 +678,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies())) .either(Either::left, r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); }*/ - private PolicyTypeDefinition validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) { Either latestPolicyTypeByType = policyTypeOperation.getLatestPolicyTypeByType(policyTypeName); - if(latestPolicyTypeByType.isRight()){ + if (latestPolicyTypeByType.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(latestPolicyTypeByType.right().value())); } return validatePolicyTypeNotExcluded(latestPolicyTypeByType.left().value(), component); @@ -737,19 +690,21 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName) .either(l -> validatePolicyTypeNotExcluded(l, component), r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); }*/ - private PolicyTypeDefinition validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) { if (getExcludedPolicyTypesByComponent(component).contains(policyType.getType())) { - throw new ByActionStatusComponentException(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component)); + throw new ByActionStatusComponentException(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), + getComponentOrResourceTypeName(component)); } return policyType; } private String getComponentOrResourceTypeName(Component component) { - return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() : ((Resource) component).getResourceType().name(); + return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() + : ((Resource) component).getResourceType().name(); } - private Component validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) { + private Component validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, + boolean shouldLock) { Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId); validateComponentIsTopologyTemplate(component); validateCanWorkOnComponent(component, userId); @@ -775,13 +730,12 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return Either.right(r); }); }*/ - private Component validateComponentIsTopologyTemplate(Component component) { if (!component.isTopologyTemplate()) { log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ", - component.getToscaType()); + component.getToscaType()); throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES, - "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType()); + "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType()); } return component; } @@ -800,7 +754,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } private Component validateComponentExists(ComponentTypeEnum componentType, String componentId) { - ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnorePolicies(false); filter.setIgnoreUsers(false); @@ -809,7 +762,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return validateComponentExists(componentId, componentType, filter); } - private PolicyDefinition validateAndUpdatePolicy(Component component, PolicyDefinition policy) { PolicyDefinition policyById = getPolicyById(component, policy.getUniqueId()); PolicyDefinition policyDefinition = validateUpdatePolicyBeforeUpdate(policy, policyById, component.getPolicies()); @@ -823,34 +775,33 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { .left() .bind(p -> updatePolicyOfComponent(component, p)); }*/ - private PolicyDefinition validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) { - PolicyDefinition policyById = getPolicyById(component, policyId); policyById = validateUpdatePolicyPropertiesBeforeUpdate(policyById, properties); return updatePolicyOfComponent(component.getUniqueId(), policyById); } private PolicyDefinition updatePolicyOfComponent(String componentId, PolicyDefinition policy) { - return toscaOperationFacade.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.MINOR) - .left() - .on(ce->componentExceptionPolicyDefinition(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(ce)))); + return toscaOperationFacade.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.MINOR).left() + .on(ce -> componentExceptionPolicyDefinition(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(ce)))); } private PolicyDefinition 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. "); + log.error( + "#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. "); throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND); } return updatePropertyValues(policy, newProperties); } private PolicyDefinition updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { - - Map oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity())); + 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. ", policy.getName()); + log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ", + policy.getName()); throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName()); } String newPropertyValueEither = updateInputPropertyObjectValue(newProperty); @@ -865,10 +816,11 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } private PolicyDefinition updatePolicyOfComponent(Component component, PolicyDefinition policy) { - - Either updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy, PromoteVersionEnum.MINOR); + Either updatePolicyRes = toscaOperationFacade + .updatePolicyOfComponent(component.getUniqueId(), policy, PromoteVersionEnum.MINOR); if (updatePolicyRes.isRight()) { - log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyRes.right().value()); + log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), + component.getName(), updatePolicyRes.right().value()); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value())); } else { log.trace("#updatePolicyOfComponent - the policy with the name {} was updated. ", updatePolicyRes.left().value().getName()); @@ -879,7 +831,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { private PolicyDefinition 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); + log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(), + component.getName(), updatePolicyStatus); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(updatePolicyStatus)); } else { log.trace("#removePolicyFromComponent - the policy with the name {} was deleted. ", updatePolicyStatus); @@ -887,10 +840,11 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { } } - private PolicyDefinition validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map policies) { - - Either policyDefinitionActionStatusEither = validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies); - if(policyDefinitionActionStatusEither.isRight()){ + private PolicyDefinition validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, + Map policies) { + Either policyDefinitionActionStatusEither = validatePolicyFields(recievedPolicy, + new PolicyDefinition(oldPolicy), policies); + if (policyDefinitionActionStatusEither.isRight()) { throw new ByActionStatusComponentException(policyDefinitionActionStatusEither.right().value(), recievedPolicy.getName()); } return policyDefinitionActionStatusEither.left().value(); @@ -901,13 +855,12 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { .right() .bind(r -> Either.right(componentsUtils.getResponseFormat(r, recievedPolicy.getName()))); }*/ - - private PolicyDefinition updateTargets(String componentId, PolicyDefinition policy, Map> targets, String policyId) { + private PolicyDefinition updateTargets(String componentId, PolicyDefinition policy, Map> targets, + String policyId) { if (policy == null) { throw new ByActionStatusComponentException(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 index b8541f18f2..6070b9ab37 100644 --- 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 @@ -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. @@ -17,9 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; +import static java.util.Collections.emptySet; + +import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.validation.UserValidations; @@ -33,12 +37,6 @@ import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static java.util.Collections.emptySet; - @Component public class PolicyTypeBusinessLogic { @@ -47,7 +45,8 @@ public class PolicyTypeBusinessLogic { private ComponentsUtils componentsUtils; private UserValidations userValidations; - public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, JanusGraphDao janusGraphDao, ComponentsUtils componentsUtils, UserValidations userValidations) { + public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, JanusGraphDao janusGraphDao, ComponentsUtils componentsUtils, + UserValidations userValidations) { this.policyTypeOperation = policyTypeOperation; this.janusGraphDao = janusGraphDao; this.componentsUtils = componentsUtils; @@ -62,16 +61,15 @@ public class PolicyTypeBusinessLogic { } public PolicyTypeDefinition getLatestPolicyTypeByType(String policyTypeName) { - return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName) - .left() - .on(e -> failOnPolicyType(e, policyTypeName)); + return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName).left().on(e -> failOnPolicyType(e, policyTypeName)); } public Set getExcludedPolicyTypes(String internalComponentType) { if (StringUtils.isEmpty(internalComponentType)) { return emptySet(); } - Map> excludedPolicyTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping(); + Map> excludedPolicyTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration() + .getExcludedPolicyTypesMapping(); Set excludedTypes = excludedPolicyTypesMapping.get(internalComponentType); return excludedTypes == null ? emptySet() : excludedTypes; } 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 377feb470d..2b9f58ce51 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 @@ -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. @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData; @@ -38,10 +40,6 @@ import org.openecomp.sdc.be.utils.TypeUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - @Component("policyTypeImportManager") public class PolicyTypeImportManager { @@ -52,9 +50,9 @@ public class PolicyTypeImportManager { private final CommonImportManager commonImportManager; private final GroupTypeOperation groupTypeOperation; - public PolicyTypeImportManager(IPolicyTypeOperation policyTypeOperation, ComponentsUtils componentsUtils, - GroupOperation groupOperation, ToscaOperationFacade toscaOperationFacade, - CommonImportManager commonImportManager, GroupTypeOperation groupTypeOperation) { + public PolicyTypeImportManager(IPolicyTypeOperation policyTypeOperation, ComponentsUtils componentsUtils, GroupOperation groupOperation, + ToscaOperationFacade toscaOperationFacade, CommonImportManager commonImportManager, + GroupTypeOperation groupTypeOperation) { this.policyTypeOperation = policyTypeOperation; this.componentsUtils = componentsUtils; this.groupOperation = groupOperation; @@ -71,12 +69,15 @@ public class PolicyTypeImportManager { return commonImportManager.createElementTypesFromYml(policyTypesYml, this::createPolicyType); } - private Either>, ResponseFormat> upsertPolicyTypesByDao(List policyTypesToCreate) { - return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, policyType -> new ImmutablePair<>(ElementTypeEnum.POLICY_TYPE, policyType.getType()), - policyTypeOperation::getLatestPolicyTypeByType, policyTypeOperation::addPolicyType, this::updatePolicyType); + private Either>, ResponseFormat> upsertPolicyTypesByDao( + List policyTypesToCreate) { + return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, + policyType -> new ImmutablePair<>(ElementTypeEnum.POLICY_TYPE, policyType.getType()), policyTypeOperation::getLatestPolicyTypeByType, + policyTypeOperation::addPolicyType, this::updatePolicyType); } - private Either updatePolicyType(PolicyTypeDefinition newPolicyType, PolicyTypeDefinition oldPolicyType) { + private Either updatePolicyType(PolicyTypeDefinition newPolicyType, + PolicyTypeDefinition oldPolicyType) { if (PolicyTypeImportUtils.isPolicyTypesEquals(newPolicyType, oldPolicyType)) { return policyTypeAlreadyExists(); } @@ -96,35 +97,29 @@ public class PolicyTypeImportManager { } if (result.isLeft()) { for (String targetId : policyType.getTargets()) { - boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft(); - - if (!isValid) { // check if it is a groupType - final Either groupTypeFound = groupTypeOperation - .getLatestGroupTypeByType(targetId, false); - isValid = groupTypeFound.isLeft() && !groupTypeFound.left().value().isEmpty(); - } - - 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; - } + boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft(); + if (!isValid) { // check if it is a groupType + final Either groupTypeFound = groupTypeOperation + .getLatestGroupTypeByType(targetId, false); + isValid = groupTypeFound.isLeft() && !groupTypeFound.left().value().isEmpty(); + } + 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 = policyType::setDescription; @@ -138,16 +133,12 @@ public class PolicyTypeImportManager { final Consumer> metadataSetter = policyType::setMetadata; commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter); // Targets - final Consumer > targetsSetter = policyType::setTargets; + final Consumer> targetsSetter = policyType::setTargets; commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter); - policyType.setType(groupTypeName); - policyType.setHighestVersion(true); - policyType.setVersion(TypeUtils.getFirstCertifiedVersionVersion()); } 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 c643d9f937..aca253682c 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 @@ -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. @@ -19,10 +19,16 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; 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; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator; @@ -61,14 +67,6 @@ 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.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 { @@ -80,37 +78,24 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { private static List creationRoles; private static List updateRoles; private static List contactsRoles; - private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; @Autowired - public ProductBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsBusinessLogic artifactsBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBusinessLogic, - ArtifactsOperations artifactToscaOperation, - ComponentContactIdValidator componentContactIdValidator, - ComponentNameValidator componentNameValidator, - ComponentTagsValidator componentTagsValidator, - ComponentValidator componentValidator, - ComponentIconValidator componentIconValidator, - ComponentProjectCodeValidator componentProjectCodeValidator, - ComponentDescriptionValidator componentDescriptionValidator){ - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, - interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, - componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator, - componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); + public ProductBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsBusinessLogic artifactsBusinessLogic, + ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ArtifactsOperations artifactToscaOperation, + ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentDescriptionValidator componentDescriptionValidator) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation, + interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator, + componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; - 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); @@ -121,61 +106,49 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { 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"); user = validateUser(user, CREATE_PRODUCT, product, actionEnum, false); // validate user role validateUserRole(user, product, creationRoles, actionEnum, null); - 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); + 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) { @@ -186,60 +159,53 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } 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; } - try { componentNameValidator.validateComponentNameUnique(user, product, actionEnum); } catch (ComponentException exp) { return Either.right(exp.getResponseFormat()); } - // 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; } - componentTagsValidator.validateAndCorrectField(user, product, actionEnum); - try { componentProjectCodeValidator.validateAndCorrectField(user, product, actionEnum); } catch (ComponentException exp) { @@ -249,38 +215,32 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { 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; } - componentDescriptionValidator.validateAndCorrectField(user, product, actionEnum); - return Either.left(true); } public Either, ResponseFormat> validateProductNameExists(String productName, String userId) { - validateUserExists(userId); - Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); + Either dataModelResponse = toscaOperationFacade + .validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); // DE242223 janusGraphDao.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())); - + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); return Either.right(responseFormat); } @@ -292,7 +252,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); return Either.right(responseFormat); } - boolean isProductCreatorInContacts = false; String modifierUserId = user.getUserId(); for (String contact : contacts) { @@ -304,35 +263,30 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } 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()); + 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; - try{ + try { contactUser = validateUserExists(contact); validateUserRole(contactUser, contactsRoles); - } catch(ByActionStatusComponentException e){ + } catch (ByActionStatusComponentException e) { log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, e.getActionStatus()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); throw new ByActionStatusComponentException(e.getActionStatus(), e.getParams()); } } - 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(String::toLowerCase) - .collect(Collectors.toList()); + List tempContacts = contacts.stream().map(String::toLowerCase).collect(Collectors.toList()); ValidationUtils.removeDuplicateFromList(tempContacts); product.setContacts(tempContacts); - return Either.left(true); } @@ -349,7 +303,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { if (!ValidationUtils.validateStringNotEmpty(catName)) { // error missing cat name log.debug("Missing category name for product: {}", product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue()); componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); return Either.right(responseFormat); } @@ -372,7 +327,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { // 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); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); return Either.right(responseFormat); } Set subcatEntry = catEntry.get(subCatName); @@ -385,7 +340,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { String groupName = group.getName(); if (!ValidationUtils.validateStringNotEmpty(groupName)) { // 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()); + 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); @@ -398,9 +354,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } } } // for end of checking duplicated - // validate existence - Either, ActionStatus> allProductCategories = elementDao.getAllProductCategories(); + // 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()); @@ -409,9 +365,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } 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; @@ -426,7 +382,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { // copy data categoryDefinition = new CategoryDefinition(catInDb); SubCategoryDefinition subCategory = null; - Map> subcats = entry.getValue(); for (Map.Entry> subcat : subcats.entrySet()) { subcatExist = false; @@ -453,9 +408,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } if (!groupExist) { // error grouping isn't defined + // in JanusGraph - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group); - componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + 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); @@ -465,7 +424,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } if (!subcatExist) { // error sub category isn't defined in JanusGraph - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey()); + 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); } @@ -476,7 +437,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } if (!catExist) { // error category isn't defined in JanusGraph - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey()); + 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); } @@ -490,16 +452,15 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { String ecompErrorContext = "Get product"; validateUserNotEmpty(user, ecompErrorContext); validateUserExists(user); - Either storageStatus = toscaOperationFacade.getToscaElement(productId); - if (storageStatus.isRight()) { log.debug("failed to get resource by id {}", productId); if (storageStatus.right().value() == 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.right( + componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); } } return Either.left(storageStatus.left().value()); @@ -509,12 +470,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { String ecompErrorContext = "Delete product"; validateUserNotEmpty(user, ecompErrorContext); validateUserExists(user); - 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 + .right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); } return Either.left(storageStatus.left().value()); } @@ -522,28 +482,27 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { 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); + 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); + 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); + 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); } @@ -551,49 +510,55 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { 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); + 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); + 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); + 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) { + private Either validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, + AuditingActionEnum actionEnum) { componentTagsValidator.validateAndCorrectField(user, product, actionEnum); 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) { @@ -606,28 +571,25 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); return Either.right(responseFormat); } - Either storageStatus = toscaOperationFacade.getToscaElement(productId); if (storageStatus.isRight()) { if (storageStatus.right().value() == StorageOperationStatus.NOT_FOUND) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase())); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase())); } - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), "")); + 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()); + 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 lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata"); @@ -646,69 +608,57 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } 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) { @@ -731,9 +681,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { currentProduct.setName(updatedProductName); tags = updatedProductName; updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName); - currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(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(); @@ -759,13 +711,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { } private Either validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) { - Either validateCategoryResponse = validateGrouping(user, updatedProduct, null); if (validateCategoryResponse.isRight()) { ResponseFormat errorResponse = validateCategoryResponse.right().value(); return Either.right(errorResponse); } - List categoryUpdated = updatedProduct.getCategories(); if (categoryUpdated != null) { currentProduct.setCategories(categoryUpdated); @@ -794,7 +744,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { List tagsCurrent = currentProduct.getTags(); if (tagsUpdated != null) { if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { - Either validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null); + Either validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), + null); if (validatResponse.isRight()) { ResponseFormat errorRespons = validatResponse.right().value(); return Either.right(errorRespons); @@ -813,10 +764,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { public Either getProductByNameAndVersion(String productName, String productVersion, String userId) { validateUserExists(userId); - Either storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion); + 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)); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), + productName)); } Product product = storageStatus.left().value(); return Either.left(product); @@ -834,9 +788,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic { @Override public Either getUiComponentDataTransferByComponentId(String componentId, - List dataParamsToReturn) { + List dataParamsToReturn) { // TODO Auto-generated method stub return null; } - } 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 66a6a27e16..baab08d0cd 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 @@ -17,11 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import com.google.gson.JsonElement; import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; @@ -59,32 +63,19 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - - @org.springframework.stereotype.Component("propertyBusinessLogic") public class PropertyBusinessLogic extends BaseBusinessLogic { private static final String CREATE_PROPERTY = "CreateProperty"; - private static final Logger log = Logger.getLogger(PropertyBusinessLogic.class); - private static final String EMPTY_VALUE = null; @Autowired - public PropertyBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public PropertyBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); } public Map getAllDataTypes() { @@ -100,54 +91,39 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { * @param userId * @return either properties or response format */ - - public Either, ResponseFormat> addPropertyToComponent(String componentId, - String propertyName, + public Either, ResponseFormat> addPropertyToComponent(String componentId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) { Either, ResponseFormat> result = null; - validateUserExists(userId); - - Either serviceElement = - toscaOperationFacade.getToscaElement(componentId); + Either serviceElement = toscaOperationFacade.getToscaElement(componentId); if (serviceElement.isRight()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); return result; } Component component = serviceElement.left().value(); NodeTypeEnum nodeType = component.getComponentType().getNodeType(); - StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType ); + StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType); if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId); log.info("Failed to lock component {}. Error - {}", componentId, lockResult); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } - try { if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return result; } - List properties = component.getProperties(); - - if(CollectionUtils.isEmpty(properties)) { + if (CollectionUtils.isEmpty(properties)) { properties = new ArrayList<>(); } - - if(isPropertyExistInComponent(properties, propertyName)) { - - result = - Either.right(componentsUtils.getResponseFormat(ActionStatus - .PROPERTY_ALREADY_EXIST, propertyName)); + if (isPropertyExistInComponent(properties, propertyName)) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName)); return result; - } else { - Map allDataTypes = getAllDataTypes(applicationDataTypeCache); - // validate property default values Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, allDataTypes); if (defaultValuesValidation.isRight()) { @@ -170,21 +146,16 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } String convertedValue = null; if (newPropertyDefinition.getDefaultValue() != null) { - convertedValue = converter.convert( - newPropertyDefinition.getDefaultValue(), innerType, allDataTypes); + convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes); newPropertyDefinition.setDefaultValue(convertedValue); } } } - Either addPropertyEither = - toscaOperationFacade - .addPropertyToComponent(propertyName, newPropertyDefinition, component); - + Either addPropertyEither = toscaOperationFacade + .addPropertyToComponent(propertyName, newPropertyDefinition, component); if (addPropertyEither.isRight()) { - log.info("Failed to add new property {}. Error - {}", componentId, - addPropertyEither.right().value()); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus - .GENERAL_ERROR)); + log.info("Failed to add new property {}. Error - {}", componentId, addPropertyEither.right().value()); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } } @@ -200,67 +171,58 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { /** * Copies a list of properties to a component. * - * @param component the component to add the copied properties + * @param component the component to add the copied properties * @param propertiesToCopyList the properties to be copied * @return the updated component with the copied properties. * @throws ToscaOperationException when a problem happens during the copy operation */ - public Component copyPropertyToComponent(final Component component, - final List propertiesToCopyList) throws ToscaOperationException { + public Component copyPropertyToComponent(final Component component, final List propertiesToCopyList) + throws ToscaOperationException { return copyPropertyToComponent(component, propertiesToCopyList, true); } /** * Copies a list of properties to a component. * - * @param component the component to add the copied properties + * @param component the component to add the copied properties * @param propertiesToCopyList the properties to be copied - * @param refreshComponent refresh the component from database after update - * @return the component refreshed from database if refreshComponent is {@code true}, the same component reference - * otherwise + * @param refreshComponent refresh the component from database after update + * @return the component refreshed from database if refreshComponent is {@code true}, the same component reference otherwise * @throws ToscaOperationException when a problem happens during the copy operation */ - public Component copyPropertyToComponent(final Component component, - final List propertiesToCopyList, + public Component copyPropertyToComponent(final Component component, final List propertiesToCopyList, final boolean refreshComponent) throws ToscaOperationException { if (CollectionUtils.isEmpty(propertiesToCopyList)) { return component; } - for (final PropertyDefinition propertyDefinition : propertiesToCopyList) { copyPropertyToComponent(component, propertyDefinition); } - if (refreshComponent) { return toscaOperationFacade.getToscaElement(component.getUniqueId()).left().value(); } - return component; } /** * Copies one property to a component. * - * @param component the component to add the copied property + * @param component the component to add the copied property * @param propertyDefinition the property to be copied * @throws ToscaOperationException when a problem happens during the copy operation */ - private void copyPropertyToComponent(final Component component, - final PropertyDefinition propertyDefinition) throws ToscaOperationException { + private void copyPropertyToComponent(final Component component, final PropertyDefinition propertyDefinition) throws ToscaOperationException { final PropertyDefinition copiedPropertyDefinition = new PropertyDefinition(propertyDefinition); final String componentId = component.getUniqueId(); final String propertyName = copiedPropertyDefinition.getName(); - copiedPropertyDefinition.setUniqueId( - UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName) - ); + copiedPropertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName)); copiedPropertyDefinition.setParentUniqueId(componentId); final Either operationResult = toscaOperationFacade .addPropertyToComponent(propertyName, copiedPropertyDefinition, component); if (operationResult.isRight()) { - final String error = String.format( - "Failed to add copied property '%s' to component '%s'. Operation status: '%s'", - propertyDefinition.getUniqueId(), componentId, operationResult.right().value() - ); + final String error = String + .format("Failed to add copied property '%s' to component '%s'. Operation status: '%s'", propertyDefinition.getUniqueId(), componentId, + operationResult.right().value()); log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, PropertyBusinessLogic.class.getName(), "catalog-be", error); throw new ToscaOperationException(error, operationResult.right().value()); } @@ -274,50 +236,40 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { * @param userId * @return either properties or response format */ - public Either, ResponseFormat> getComponentProperty(String componentId, String propertyId, String userId) { - validateUserExists(userId); // Get the resource from DB - Either status = - toscaOperationFacade.getToscaElement(componentId); + Either status = toscaOperationFacade.getToscaElement(componentId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } Component component = status.left().value(); List properties = component.getProperties(); - if(CollectionUtils.isEmpty(properties)) { + if (CollectionUtils.isEmpty(properties)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); } - - for(PropertyDefinition property : properties) { - if(property.getUniqueId().equals(propertyId)) { + for (PropertyDefinition property : properties) { + if (property.getUniqueId().equals(propertyId)) { return Either.left(new EntryData<>(property.getName(), property)); } } return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); } - - public Either, ResponseFormat> getPropertiesList(String componentId, - String userId) { + public Either, ResponseFormat> getPropertiesList(String componentId, String userId) { validateUserExists(userId); - // Get the resource from DB ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreProperties(false); - Either status = - toscaOperationFacade.getToscaElement(componentId); + Either status = toscaOperationFacade.getToscaElement(componentId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } Component component = status.left().value(); List properties = component.getProperties(); - return Either.left(properties); } - /** * delete property of component from graph * @@ -326,13 +278,10 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { * @param userId * @return either properties or response format */ - - public Either, ResponseFormat> deletePropertyFromComponent(String componentId, String propertyId, String userId) { - + public Either, ResponseFormat> deletePropertyFromComponent(String componentId, String propertyId, + String userId) { Either, ResponseFormat> result = null; - validateUserExists(userId); - // Get the resource from DB Either getComponentRes = toscaOperationFacade.getToscaElement(componentId); if (getComponentRes.isRight()) { @@ -343,46 +292,36 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { NodeTypeEnum nodeType = component.getComponentType().getNodeType(); StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType); if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), - componentId); + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } - try { // verify that resource is checked-out and the user is the last + // updater if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return result; } - // verify property exist in resource - Either, ResponseFormat> statusGetProperty = - getComponentProperty(componentId, propertyId, userId); + Either, ResponseFormat> statusGetProperty = getComponentProperty(componentId, propertyId, userId); if (statusGetProperty.isRight()) { result = Either.right(statusGetProperty.right().value()); return result; } - Map.Entry propertyDefinitionEntry = statusGetProperty.left().value(); - // verify that the property is not used by operation if (isPropertyUsedByOperation(component, propertyDefinitionEntry.getValue())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .PROPERTY_USED_BY_OPERATION)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_USED_BY_OPERATION)); } - - StorageOperationStatus status = - toscaOperationFacade.deletePropertyOfComponent(component, propertyDefinitionEntry.getKey()); + StorageOperationStatus status = toscaOperationFacade.deletePropertyOfComponent(component, propertyDefinitionEntry.getKey()); if (status != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils - .convertFromStorageResponse(status), component.getName())); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); return result; } result = Either.left(propertyDefinitionEntry); return result; - } finally { commitOrRollback(result); // unlock component @@ -390,58 +329,48 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } } - public boolean isPropertyUsedByOperation(Component component, - PropertyDefinition propertyDefinitionEntry) { - + public boolean isPropertyUsedByOperation(Component component, PropertyDefinition propertyDefinitionEntry) { // Component's own interfaces Map interfaces = component.getInterfaces(); - if(MapUtils.isNotEmpty(interfaces)){ - for(Map.Entry interfaceEntry : interfaces.entrySet()) { - if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) { - return true; + if (MapUtils.isNotEmpty(interfaces)) { + for (Map.Entry interfaceEntry : interfaces.entrySet()) { + if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) { + return true; + } } - } } - // Component's child's component interfaces - if(isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)){ + if (isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)) { return true; } - // Component's parent's component interfaces Either, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId()); - if(componentList.isLeft()){ + if (componentList.isLeft()) { for (Component parentComponent : componentList.left().value()) { - if(isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)){ + if (isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)) { return true; } } } - return false; } - private boolean isPropertyUsedInCIInterfaces(Map> componentInstanceInterfaces, PropertyDefinition propertyDefinitionEntry){ + private boolean isPropertyUsedInCIInterfaces(Map> componentInstanceInterfaces, + PropertyDefinition propertyDefinitionEntry) { Optional isPropertyExistInOperationInterface = Optional.empty(); - if(MapUtils.isNotEmpty(componentInstanceInterfaces)){ + if (MapUtils.isNotEmpty(componentInstanceInterfaces)) { isPropertyExistInOperationInterface = componentInstanceInterfaces.entrySet().stream() - .flatMap(interfaceEntry -> interfaceEntry.getValue().stream()) - .filter(instanceInterface -> isPropertyExistInOperationInterface(propertyDefinitionEntry, instanceInterface)) - .findAny(); + .flatMap(interfaceEntry -> interfaceEntry.getValue().stream()) + .filter(instanceInterface -> isPropertyExistInOperationInterface(propertyDefinitionEntry, instanceInterface)).findAny(); } return isPropertyExistInOperationInterface.isPresent(); } - private boolean isPropertyExistInOperationInterface(PropertyDefinition propertyDefinition, - InterfaceDefinition interfaceDefinition) { - Map operations = - interfaceDefinition.getOperations(); - for(Map.Entry operationEntry : operations - .entrySet()) { - Optional inputWithDeletedPropertyCandidate = - getInputWithDeclaredProperty(propertyDefinition, operationEntry); - - if(inputWithDeletedPropertyCandidate.isPresent()) { + private boolean isPropertyExistInOperationInterface(PropertyDefinition propertyDefinition, InterfaceDefinition interfaceDefinition) { + Map operations = interfaceDefinition.getOperations(); + for (Map.Entry operationEntry : operations.entrySet()) { + Optional inputWithDeletedPropertyCandidate = getInputWithDeclaredProperty(propertyDefinition, operationEntry); + if (inputWithDeletedPropertyCandidate.isPresent()) { return true; } } @@ -450,17 +379,14 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { private Optional getInputWithDeclaredProperty(PropertyDefinition propertyDefinition, Map.Entry operationEntry) { - ListDataDefinition inputs = - operationEntry.getValue().getInputs(); - List operationInputsList = - Objects.isNull(inputs) ? null : inputs.getListToscaDataDefinition(); - - if(CollectionUtils.isEmpty(operationInputsList)) { + ListDataDefinition inputs = operationEntry.getValue().getInputs(); + List operationInputsList = Objects.isNull(inputs) ? null : inputs.getListToscaDataDefinition(); + if (CollectionUtils.isEmpty(operationInputsList)) { return Optional.empty(); } - - return operationInputsList.stream().filter(input -> input.getInputId().equals(propertyDefinition.getUniqueId()) - || (input.getSourceProperty() != null && input.getSourceProperty().equals(propertyDefinition.getUniqueId()))).findAny(); + return operationInputsList.stream().filter( + input -> input.getInputId().equals(propertyDefinition.getUniqueId()) || (input.getSourceProperty() != null && input.getSourceProperty() + .equals(propertyDefinition.getUniqueId()))).findAny(); } /** @@ -472,59 +398,46 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { * @param userId * @return either properties or response format */ - - public Either, ResponseFormat> updateComponentProperty(String componentId, - String propertyId, - PropertyDefinition newPropertyDefinition, - String userId) { - + public Either, ResponseFormat> updateComponentProperty(String componentId, String propertyId, + PropertyDefinition newPropertyDefinition, + String userId) { Either, ResponseFormat> result = null; - - Either status = toscaOperationFacade.getToscaElement( - componentId); + Either status = toscaOperationFacade.getToscaElement(componentId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } Component component = status.left().value(); NodeTypeEnum nodeType = component.getComponentType().getNodeType(); - if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } - StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType); if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), - componentId); + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } - try { - Either, ResponseFormat> statusGetProperty = - getComponentProperty(componentId, propertyId, userId); + Either, ResponseFormat> statusGetProperty = getComponentProperty(componentId, propertyId, userId); if (statusGetProperty.isRight()) { result = Either.right(statusGetProperty.right().value()); return result; } String propertyName = statusGetProperty.left().value().getKey(); - - Either either = - toscaOperationFacade.updatePropertyOfComponent(component, newPropertyDefinition); + Either either = toscaOperationFacade + .updatePropertyOfComponent(component, newPropertyDefinition); if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), component.getName())); + result = Either.right(componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), component.getName())); return result; } - EntryData property = new EntryData<>(propertyName, either.left().value()); result = Either.left(property); return result; - } finally { commitOrRollback(result); graphLockOperation.unlockComponent(componentId, nodeType); } - } /** @@ -550,41 +463,32 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { /** * Updates a component property. * - * @param componentId the component id that owns the property + * @param componentId the component id that owns the property * @param propertyDefinition the existing property to update * @return the updated property - * @throws BusinessLogicException if the component was not found or if there was a problem during the update - * operation. + * @throws BusinessLogicException if the component was not found or if there was a problem during the update operation. */ - public PropertyDefinition updateComponentProperty(final String componentId, - final PropertyDefinition propertyDefinition) - throws BusinessLogicException { + public PropertyDefinition updateComponentProperty(final String componentId, final PropertyDefinition propertyDefinition) + throws BusinessLogicException { final Component component = findComponentById(componentId).orElse(null); if (component == null) { - throw new BusinessLogicException( - componentsUtils.getResponseFormatByResource(ActionStatus.RESOURCE_NOT_FOUND, componentId)); + throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(ActionStatus.RESOURCE_NOT_FOUND, componentId)); } - final Either updateResultEither = - toscaOperationFacade.updatePropertyOfComponent(component, propertyDefinition); + final Either updateResultEither = toscaOperationFacade + .updatePropertyOfComponent(component, propertyDefinition); if (updateResultEither.isRight()) { - final ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(updateResultEither.right().value()), component.getName() - ); + final ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateResultEither.right().value()), component.getName()); throw new BusinessLogicException(responseFormat); } - return updateResultEither.left().value(); } private boolean isPropertyExistInComponent(List properties, String propertyName) { - if(CollectionUtils.isEmpty(properties)) { + if (CollectionUtils.isEmpty(properties)) { return false; } - - Optional propertyCandidate = - properties.stream().filter(property -> property.getName().equals(propertyName)) - .findAny(); - + Optional propertyCandidate = properties.stream().filter(property -> property.getName().equals(propertyName)).findAny(); return propertyCandidate.isPresent(); } @@ -593,7 +497,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { if (jsonElement == null || jsonElement.isJsonNull()) { return EMPTY_VALUE; } - if(jsonElement.toString().isEmpty()){ + if (jsonElement.toString().isEmpty()) { return ""; } return jsonElement.toString(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java index e231ed7ffe..9a83566166 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.Map; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; @@ -27,40 +27,33 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.Map; - @Component("relationshipTypeBusinessLogic") public class RelationshipTypeBusinessLogic { - private final RelationshipTypeOperation relationshipTypeOperation; protected final ComponentsUtils componentsUtils; + private final RelationshipTypeOperation relationshipTypeOperation; @Autowired - public RelationshipTypeBusinessLogic(RelationshipTypeOperation relationshipTypeOperation, - ComponentsUtils componentsUtils) { + public RelationshipTypeBusinessLogic(RelationshipTypeOperation relationshipTypeOperation, ComponentsUtils componentsUtils) { this.relationshipTypeOperation = relationshipTypeOperation; this.componentsUtils = componentsUtils; } public Either, ResponseFormat> getAllRelationshipTypes() { - Either, JanusGraphOperationStatus> allRelationshipTypes = - relationshipTypeOperation.getAllRelationshipTypes(); + Either, JanusGraphOperationStatus> allRelationshipTypes = relationshipTypeOperation + .getAllRelationshipTypes(); if (allRelationshipTypes.isRight()) { JanusGraphOperationStatus operationStatus = allRelationshipTypes.right().value(); if (JanusGraphOperationStatus.NOT_FOUND == operationStatus) { - BeEcompErrorManager.getInstance().logInternalDataError("FetchRelationshipTypes", "Relationship types " - + "are " - + "not loaded", - BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInternalDataError("FetchRelationshipTypes", "Relationship types " + "are " + "not loaded", + BeEcompErrorManager.ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); } else { - BeEcompErrorManager.getInstance().logInternalFlowError("FetchRelationshipTypes", "Failed to fetch " - + "relationship types", - BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInternalFlowError("FetchRelationshipTypes", "Failed to fetch " + "relationship types", + BeEcompErrorManager.ErrorSeverity.ERROR); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } } return Either.left(allRelationshipTypes.left().value()); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java index 993d0136f6..6e4d554d98 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.List; +import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -29,9 +30,6 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Map; - @Component("relationshipTypeImportManager") public class RelationshipTypeImportManager { @@ -40,73 +38,62 @@ public class RelationshipTypeImportManager { private final ComponentsUtils componentsUtils; @Autowired - public RelationshipTypeImportManager(RelationshipTypeOperation relationshipTypeOperation, - CommonImportManager commonImportManager, ComponentsUtils componentsUtils) { + public RelationshipTypeImportManager(RelationshipTypeOperation relationshipTypeOperation, CommonImportManager commonImportManager, + ComponentsUtils componentsUtils) { this.relationshipTypeOperation = relationshipTypeOperation; this.commonImportManager = commonImportManager; this.componentsUtils = componentsUtils; } - public Either>, ResponseFormat> createRelationshipTypes( - String relationshipYml) { + public Either>, ResponseFormat> createRelationshipTypes(String relationshipYml) { return createRelationshipTypes(relationshipYml, false); } - private Either>, ResponseFormat> createRelationshipTypes( - String relationshipTypeYml, boolean inTransaction) { - return commonImportManager.createElementTypes(relationshipTypeYml, - relationshipTypesFromYml -> createRelationshipTypesFromYml(relationshipTypeYml), - relationshipTypesToCreate -> createRelationshipTypesByDao(relationshipTypesToCreate, - inTransaction), ElementTypeEnum.RELATIONSHIP_TYPE); + private Either>, ResponseFormat> createRelationshipTypes(String relationshipTypeYml, + boolean inTransaction) { + return commonImportManager + .createElementTypes(relationshipTypeYml, relationshipTypesFromYml -> createRelationshipTypesFromYml(relationshipTypeYml), + relationshipTypesToCreate -> createRelationshipTypesByDao(relationshipTypesToCreate, inTransaction), + ElementTypeEnum.RELATIONSHIP_TYPE); } - private Either, ActionStatus> createRelationshipTypesFromYml( - String relationshipTypeYml) { - return commonImportManager.createElementTypesFromYml(relationshipTypeYml, - this::createRelationshipType); + private Either, ActionStatus> createRelationshipTypesFromYml(String relationshipTypeYml) { + return commonImportManager.createElementTypesFromYml(relationshipTypeYml, this::createRelationshipType); } private Either>, ResponseFormat> createRelationshipTypesByDao( - List relationshipTypesToCreate, boolean inTransaction) { + List relationshipTypesToCreate, boolean inTransaction) { return commonImportManager.createElementTypesByDao(relationshipTypesToCreate, this::validateRelationshipType, - relationshipType -> new ImmutablePair<>(ElementTypeEnum.RELATIONSHIP_TYPE, relationshipType.getType()), - relationshipTypeName -> relationshipTypeOperation.getRelationshipTypeByName(relationshipTypeName) - .right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus), - relationshipType -> relationshipTypeOperation.addRelationshipType(relationshipType, inTransaction), - (newRelationshipType, oldRelationshipType) -> relationshipTypeOperation - .updateRelationshipType(newRelationshipType, oldRelationshipType, inTransaction)); + relationshipType -> new ImmutablePair<>(ElementTypeEnum.RELATIONSHIP_TYPE, relationshipType.getType()), + relationshipTypeName -> relationshipTypeOperation.getRelationshipTypeByName(relationshipTypeName).right() + .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus), + relationshipType -> relationshipTypeOperation.addRelationshipType(relationshipType, inTransaction), + (newRelationshipType, oldRelationshipType) -> relationshipTypeOperation + .updateRelationshipType(newRelationshipType, oldRelationshipType, inTransaction)); } - private Either validateRelationshipType(RelationshipTypeDefinition relationshipType) { Either result = Either.left(ActionStatus.OK); if (relationshipType.getType() == null) { - ResponseFormat responseFormat = - componentsUtils.getResponseFormat(ActionStatus.MISSING_RELATIONSHIP_TYPE, relationshipType.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_RELATIONSHIP_TYPE, relationshipType.getType()); result = Either.right(responseFormat); } return result; } - private RelationshipTypeDefinition createRelationshipType(String relationshipTypeName, - Map toscaJson) { + private RelationshipTypeDefinition createRelationshipType(String relationshipTypeName, Map toscaJson) { RelationshipTypeDefinition relationshipType = new RelationshipTypeDefinition(); - relationshipType.setType(relationshipTypeName); - // Description - commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), - relationshipType::setDescription); + commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), relationshipType::setDescription); // Derived From - commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), - relationshipType::setDerivedFrom); + commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), relationshipType::setDerivedFrom); // Properties commonImportManager.setPropertiesMap(toscaJson, relationshipType::setProperties); //valid-target-types - if(toscaJson.get("valid_target_types") instanceof List) + if (toscaJson.get("valid_target_types") instanceof List) { relationshipType.setValidTargetTypes((List) toscaJson.get("valid_target_types")); - + } return relationshipType; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java index f3aca5696a..e5d704709d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java @@ -13,10 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.impl; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; @@ -41,39 +49,23 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - @Component("requirementBusinessLogic") public class RequirementBusinessLogic extends BaseBusinessLogic { + private static final Logger LOGGER = LoggerFactory.getLogger(RequirementBusinessLogic.class); - private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS - = "Failed to lock component {}. Response is {}"; + private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS = "Failed to lock component {}. Response is {}"; private static final String DELETE_REQUIREMENTS = "deleteRequirement"; private static final String GET_REQUIREMENTS = "getRequirements"; - private static final String EXCEPTION_OCCURRED_DURING_REQUIREMENTS - = "Exception occurred during {}. Response is {}"; - + private static final String EXCEPTION_OCCURRED_DURING_REQUIREMENTS = "Exception occurred during {}. Response is {}"; private RequirementOperation requirementOperation; private RequirementValidation requirementValidation; @Autowired - public RequirementBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public RequirementBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); } @Autowired @@ -86,63 +78,52 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { this.requirementValidation = requirementValidation; } - public Either, ResponseFormat> createRequirements( - String componentId, List requirementDefinitions, - User user, String errorContext, boolean lock) { + public Either, ResponseFormat> createRequirements(String componentId, + List requirementDefinitions, User user, + String errorContext, boolean lock) { validateUserExists(user.getUserId()); - Either componentEither - = getComponentDetails(componentId); + Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - Either requirementsValidationEither = requirementValidation - .validateRequirements(requirementDefinitions, storedComponent, false); + .validateRequirements(requirementDefinitions, storedComponent, false); if (requirementsValidationEither.isRight()) { return Either.right(requirementsValidationEither.right().value()); } - - Either lockResult = lockComponentResult(lock, - storedComponent, errorContext); + Either lockResult = lockComponentResult(lock, storedComponent, errorContext); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } - try { Either, StorageOperationStatus> result; List requirementsListStoredInComponent = null; - Map> storedComponentRequirements - = storedComponent.getRequirements(); + Map> storedComponentRequirements = storedComponent.getRequirements(); if (org.apache.commons.collections.MapUtils.isNotEmpty(storedComponentRequirements)) { RequirementDefinition requirementDefinitionToGetType = requirementDefinitions.get(0); - if(Objects.isNull(requirementDefinitionToGetType)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + if (Objects.isNull(requirementDefinitionToGetType)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } - requirementsListStoredInComponent - = getRequirementStoredInComponentByType(requirementDefinitionToGetType - .getCapability(), storedComponentRequirements); + requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToGetType.getCapability(), + storedComponentRequirements); } List requirementsToReturn; - if (org.apache.commons.collections.CollectionUtils - .isNotEmpty(requirementsListStoredInComponent)) { + if (org.apache.commons.collections.CollectionUtils.isNotEmpty(requirementsListStoredInComponent)) { List requirementDefToCreate = requirementDefinitions.stream() - .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)) - .collect(Collectors.toList()); + .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList()); requirementsToReturn = requirementDefToCreate; requirementDefToCreate.addAll(requirementsListStoredInComponent); result = requirementOperation.updateRequirement(componentId, requirementDefToCreate); } else { - requirementsToReturn = requirementDefinitions.stream().map(requirementDefinition -> - initiateNewRequirement(storedComponent, requirementDefinition)) - .collect(Collectors.toList()); + requirementsToReturn = requirementDefinitions.stream() + .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList()); result = requirementOperation.addRequirement(componentId, requirementsToReturn); } if (result.isRight()) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(result.right().value(), - storedComponent.getComponentType()), "")); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), "")); } janusGraphDao.commit(); return Either.left(requirementsToReturn); @@ -152,75 +133,63 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - public Either, ResponseFormat> updateRequirements( - String componentId, List requirementDefinitions, - User user, String errorContext, boolean lock) { + public Either, ResponseFormat> updateRequirements(String componentId, + List requirementDefinitions, User user, + String errorContext, boolean lock) { validateUserExists(user.getUserId()); - Either componentEither - = getComponentDetails(componentId); + Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - Either requirementsValidationEither = requirementValidation - .validateRequirements(requirementDefinitions, storedComponent, true); + .validateRequirements(requirementDefinitions, storedComponent, true); if (requirementsValidationEither.isRight()) { return Either.right(requirementsValidationEither.right().value()); } - - Either lockResult = lockComponentResult(lock, - storedComponent, errorContext); + Either lockResult = lockComponentResult(lock, storedComponent, errorContext); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } try { Either, StorageOperationStatus> result; List requirementsListStoredInComponent = null; - Map> storedComponentRequirements - = storedComponent.getRequirements(); + Map> storedComponentRequirements = storedComponent.getRequirements(); if (org.apache.commons.collections.MapUtils.isNotEmpty(storedComponentRequirements)) { RequirementDefinition requirementDefinitionToGetType = requirementDefinitions.get(0); - if(Objects.isNull(requirementDefinitionToGetType)) { + if (Objects.isNull(requirementDefinitionToGetType)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } - requirementsListStoredInComponent - = getRequirementStoredInComponentByType(requirementDefinitionToGetType - .getCapability(), storedComponentRequirements); + requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToGetType.getCapability(), + storedComponentRequirements); } List requirementsToReturn = null; - if (org.apache.commons.collections.CollectionUtils - .isNotEmpty(requirementsListStoredInComponent)) { + if (org.apache.commons.collections.CollectionUtils.isNotEmpty(requirementsListStoredInComponent)) { List requirementDefToUpdate = new ArrayList<>(); - if (requirementDefinitions.stream().anyMatch(requirementDefinition -> - isRequirementUsedInServiceComposition(requirementDefinition, storedComponent))) { + if (requirementDefinitions.stream() + .anyMatch(requirementDefinition -> isRequirementUsedInServiceComposition(requirementDefinition, storedComponent))) { LOGGER.error("Requirement can't be edited, since it is used in service composition"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION)); } for (RequirementDefinition requirementDefinitionToUpdate : requirementDefinitions) { requirementsToReturn = requirementsListStoredInComponent.stream() - .filter(reqToUpdate -> reqToUpdate.getUniqueId() - .equals(requirementDefinitionToUpdate.getUniqueId())) - .map(requirementDefinition -> updateRequirement(requirementDefinition, - requirementDefinitionToUpdate)).collect(Collectors.toList()); - requirementsListStoredInComponent.removeIf(reqToUpdate -> - reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())); - + .filter(reqToUpdate -> reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())) + .map(requirementDefinition -> updateRequirement(requirementDefinition, requirementDefinitionToUpdate)) + .collect(Collectors.toList()); + requirementsListStoredInComponent + .removeIf(reqToUpdate -> reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())); if (CollectionUtils.isNotEmpty(requirementsToReturn)) { requirementsListStoredInComponent.addAll(requirementsToReturn); requirementDefToUpdate.addAll(requirementsListStoredInComponent); } else { - Either, ResponseFormat> updateCapTypeEither - = handleUpdateRequirementCapabilityWhenNewCapabilityExist(storedComponent, - storedComponentRequirements, - requirementsToReturn, requirementDefinitionToUpdate); + Either, ResponseFormat> updateCapTypeEither = handleUpdateRequirementCapabilityWhenNewCapabilityExist( + storedComponent, storedComponentRequirements, requirementsToReturn, requirementDefinitionToUpdate); if (updateCapTypeEither.isRight()) { return Either.right(updateCapTypeEither.right().value()); } @@ -229,22 +198,19 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { } result = requirementOperation.updateRequirement(componentId, requirementDefToUpdate); } else { - Either, ResponseFormat> requirementDefinitionToDelete - = handleRequirementCapabilityUpdateWhenNewCapabilityNotExist(requirementDefinitions, - storedComponent, storedComponentRequirements); + Either, ResponseFormat> requirementDefinitionToDelete = handleRequirementCapabilityUpdateWhenNewCapabilityNotExist( + requirementDefinitions, storedComponent, storedComponentRequirements); if (requirementDefinitionToDelete != null) { return requirementDefinitionToDelete; } - requirementsToReturn = requirementDefinitions.stream().map(requirementDefinition -> - initiateNewRequirement(storedComponent, requirementDefinition)) - .collect(Collectors.toList()); + requirementsToReturn = requirementDefinitions.stream() + .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList()); result = requirementOperation.addRequirement(componentId, requirementsToReturn); } if (result.isRight()) { janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(result.right().value(), - storedComponent.getComponentType()), "")); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), "")); } janusGraphDao.commit(); return Either.left(requirementsToReturn); @@ -254,70 +220,55 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } private Either, ResponseFormat> handleUpdateRequirementCapabilityWhenNewCapabilityExist( - org.openecomp.sdc.be.model.Component storedComponent, - Map> storedComponentRequirements, - List requirementsToReturn, - RequirementDefinition requirementDefinitionToUpdate) { + org.openecomp.sdc.be.model.Component storedComponent, Map> storedComponentRequirements, + List requirementsToReturn, RequirementDefinition requirementDefinitionToUpdate) { List requirementsListStoredInComponent; List requirementDefsToCreateOrUpdate = new ArrayList<>(); - Optional definitionOptional = storedComponentRequirements - .values().stream().flatMap(Collection::stream) - .filter(requirementDefinition -> requirementDefinition.getUniqueId() - .equals(requirementDefinitionToUpdate.getUniqueId())).findAny(); + Optional definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream) + .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())).findAny(); if (!definitionOptional.isPresent()) { - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId())); } RequirementDefinition requirementDefinitionToDelete = definitionOptional.get(); - - requirementsListStoredInComponent = getRequirementStoredInComponentByType( - requirementDefinitionToUpdate.getCapability(), storedComponentRequirements); - Either, StorageOperationStatus> deleteRequirementEither - = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete); + requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToUpdate.getCapability(), + storedComponentRequirements); + Either, StorageOperationStatus> deleteRequirementEither = deleteRequirement(storedComponent, + storedComponentRequirements, requirementDefinitionToDelete); if (deleteRequirementEither.isRight()) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteRequirementEither.right().value())); } requirementsToReturn.add(initiateNewRequirement(storedComponent, requirementDefinitionToUpdate)); - requirementDefsToCreateOrUpdate.addAll(requirementsToReturn); requirementDefsToCreateOrUpdate.addAll(requirementsListStoredInComponent); return Either.left(requirementDefsToCreateOrUpdate); } private Either, ResponseFormat> handleRequirementCapabilityUpdateWhenNewCapabilityNotExist( - List requirementDefinitions, - org.openecomp.sdc.be.model.Component storedComponent, - Map> storedComponentRequirements) { + List requirementDefinitions, org.openecomp.sdc.be.model.Component storedComponent, + Map> storedComponentRequirements) { for (RequirementDefinition requirementDefinitionToUpdate : requirementDefinitions) { - - Optional definitionOptional = storedComponentRequirements - .values().stream().flatMap(Collection::stream) - .filter(requirementDefinition -> requirementDefinition.getUniqueId() - .equals(requirementDefinitionToUpdate.getUniqueId())).findAny(); + Optional definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream) + .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())).findAny(); if (!definitionOptional.isPresent()) { - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId())); } RequirementDefinition requirementDefinitionToDelete = definitionOptional.get(); - Boolean isRequirementUsedInServiceComposition - = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent); + Boolean isRequirementUsedInServiceComposition = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent); if (isRequirementUsedInServiceComposition) { - LOGGER.error("Requirement {} can't be edited, since it is used in service composition", - requirementDefinitionToDelete.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION, - requirementDefinitionToDelete.getName())); + LOGGER.error("Requirement {} can't be edited, since it is used in service composition", requirementDefinitionToDelete.getUniqueId()); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION, requirementDefinitionToDelete.getName())); } - Either, StorageOperationStatus> deleteRequirementEither - = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete); + Either, StorageOperationStatus> deleteRequirementEither = deleteRequirement(storedComponent, + storedComponentRequirements, requirementDefinitionToDelete); if (deleteRequirementEither.isRight()) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(deleteRequirementEither.right().value())); @@ -326,30 +277,26 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { return null; } - public Either getRequirement(String componentId, - String requirementIdToGet, User user, boolean lock) { + public Either getRequirement(String componentId, String requirementIdToGet, User user, boolean lock) { validateUserExists(user.getUserId()); Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - Either lockResult = lockComponentResult(lock, storedComponent, GET_REQUIREMENTS); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } try { - - List requirementDefinitions = storedComponent.getRequirements().values().stream() - .flatMap(Collection::stream).collect(Collectors.toList()); + List requirementDefinitions = storedComponent.getRequirements().values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); if (requirementDefinitions.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId)); } - RequirementDefinition requirementDefinitionToReturn; Optional requirementDefinitionOptional = requirementDefinitions.stream() - .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToGet)).findAny(); + .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToGet)).findAny(); if (requirementDefinitionOptional.isPresent()) { requirementDefinitionToReturn = requirementDefinitionOptional.get(); } else { @@ -361,61 +308,48 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - public Either deleteRequirement(String componentId, - String requirementIdToDelete, - User user, boolean lock) { + public Either deleteRequirement(String componentId, String requirementIdToDelete, User user, + boolean lock) { validateUserExists(user.getUserId()); - Either componentEither - = getComponentDetails(componentId); + Either componentEither = getComponentDetails(componentId); if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - Either lockResult = lockComponentResult(lock, storedComponent, DELETE_REQUIREMENTS); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } - try { Map> storedComponentRequirements = storedComponent.getRequirements(); if (storedComponentRequirements.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId)); } - - Optional definitionOptional = storedComponentRequirements - .values().stream().flatMap(Collection::stream) - .filter(requirementDefinition -> requirementDefinition.getUniqueId() - .equals(requirementIdToDelete)).findAny(); + Optional definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream) + .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToDelete)).findAny(); if (!definitionOptional.isPresent()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId)); } RequirementDefinition requirementDefinitionToDelete = definitionOptional.get(); - - Boolean isRequirementUsedInServiceComposition - = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent); + Boolean isRequirementUsedInServiceComposition = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent); if (isRequirementUsedInServiceComposition) { - LOGGER.error("Requirement {} can't be deleted, since it is used in service composition", - requirementDefinitionToDelete.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, - requirementDefinitionToDelete.getName())); + LOGGER.error("Requirement {} can't be deleted, since it is used in service composition", requirementDefinitionToDelete.getUniqueId()); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, requirementDefinitionToDelete.getName())); } - - Either, StorageOperationStatus> result - = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete); + Either, StorageOperationStatus> result = deleteRequirement(storedComponent, storedComponentRequirements, + requirementDefinitionToDelete); if (result.isRight()) { janusGraphDao.rollback(); - LOGGER.error("Failed to delete requirement from component {}. Response is {}", - storedComponent.getName(), result.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils - .convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()))); + LOGGER.error("Failed to delete requirement from component {}. Response is {}", storedComponent.getName(), result.right().value()); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()))); } janusGraphDao.commit(); return Either.left(requirementDefinitionToDelete); @@ -425,37 +359,33 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND)); } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), - NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation + .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - private Either, StorageOperationStatus> deleteRequirement( - org.openecomp.sdc.be.model.Component storedComponent, Map> storedComponentRequirements, - RequirementDefinition requirementDefinitionToDelete) { - List requirementStoredInComponentByType = - getRequirementStoredInComponentByType(requirementDefinitionToDelete.getCapability(), - storedComponentRequirements); - if(requirementStoredInComponentByType == null) { + private Either, StorageOperationStatus> deleteRequirement(org.openecomp.sdc.be.model.Component storedComponent, + Map> storedComponentRequirements, + RequirementDefinition requirementDefinitionToDelete) { + List requirementStoredInComponentByType = getRequirementStoredInComponentByType( + requirementDefinitionToDelete.getCapability(), storedComponentRequirements); + if (requirementStoredInComponentByType == null) { return Either.right(StorageOperationStatus.BAD_REQUEST); } - requirementStoredInComponentByType.removeIf(requirementDefinition -> - requirementDefinition.getUniqueId().equals(requirementDefinitionToDelete.getUniqueId())); + requirementStoredInComponentByType + .removeIf(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToDelete.getUniqueId())); Either, StorageOperationStatus> result; if (requirementStoredInComponentByType.isEmpty()) { - - StorageOperationStatus operationStatus = requirementOperation.deleteRequirements(storedComponent, - requirementDefinitionToDelete.getCapability()); + StorageOperationStatus operationStatus = requirementOperation + .deleteRequirements(storedComponent, requirementDefinitionToDelete.getCapability()); if (operationStatus.equals(StorageOperationStatus.OK)) { result = Either.left(Collections.singletonList(requirementDefinitionToDelete)); } else { result = Either.right(operationStatus); } } else { - result = requirementOperation.updateRequirement(storedComponent.getUniqueId(), - requirementStoredInComponentByType); + result = requirementOperation.updateRequirement(storedComponent.getUniqueId(), requirementStoredInComponentByType); } return result; } @@ -463,8 +393,8 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { private Either getComponentDetails(String componentId) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreRequirements(false); - Either componentStorageOperationStatusEither - = toscaOperationFacade.getToscaElement(componentId, filter); + Either componentStorageOperationStatusEither = toscaOperationFacade + .getToscaElement(componentId, filter); if (componentStorageOperationStatusEither.isRight()) { StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value(); LOGGER.error("Failed to fetch component information by component id {}, Response is {}", componentId, errorStatus); @@ -473,15 +403,12 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { return Either.left(componentStorageOperationStatusEither.left().value()); } - private Either lockComponentResult(boolean lock, - org.openecomp.sdc.be.model.Component component, - String action) { + private Either lockComponentResult(boolean lock, org.openecomp.sdc.be.model.Component component, String action) { if (lock) { - try{ - lockComponent(component.getUniqueId(), component, action); - } catch (ComponentException e){ - LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), - e.getMessage()); + try { + lockComponent(component.getUniqueId(), component, action); + } catch (ComponentException e) { + LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), e.getMessage()); janusGraphDao.rollback(); throw e; } @@ -489,30 +416,29 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private List getRequirementStoredInComponentByType( - String capabilityType, Map> requirements) { - - Optional>> entryOptional - = requirements.entrySet().stream().filter(map -> map.getKey().equals(capabilityType)).findFirst(); + private List getRequirementStoredInComponentByType(String capabilityType, + Map> requirements) { + Optional>> entryOptional = requirements.entrySet().stream() + .filter(map -> map.getKey().equals(capabilityType)).findFirst(); return entryOptional.map(Map.Entry::getValue).orElse(null); - } private RequirementDefinition initiateNewRequirement(org.openecomp.sdc.be.model.Component component, RequirementDefinition requirementDefinition) { - if (StringUtils.isEmpty(requirementDefinition.getUniqueId())) + if (StringUtils.isEmpty(requirementDefinition.getUniqueId())) { requirementDefinition.setUniqueId(UUID.randomUUID().toString()); - if (StringUtils.isEmpty(requirementDefinition.getOwnerId())) + } + if (StringUtils.isEmpty(requirementDefinition.getOwnerId())) { requirementDefinition.setOwnerId(component.getUniqueId()); - if (StringUtils.isEmpty(requirementDefinition.getOwnerName())) + } + if (StringUtils.isEmpty(requirementDefinition.getOwnerName())) { requirementDefinition.setOwnerName(component.getName()); + } requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences()); return requirementDefinition; } - private RequirementDefinition updateRequirement(RequirementDefinition storedRequirement, - RequirementDefinition requirementToUpdate) { + private RequirementDefinition updateRequirement(RequirementDefinition storedRequirement, RequirementDefinition requirementToUpdate) { storedRequirement.setName(requirementToUpdate.getName()); storedRequirement.setCapability(requirementToUpdate.getCapability()); storedRequirement.setNode(requirementToUpdate.getNode()); @@ -524,15 +450,14 @@ public class RequirementBusinessLogic extends BaseBusinessLogic { private Boolean isRequirementUsedInServiceComposition(RequirementDefinition requirementDefinition, org.openecomp.sdc.be.model.Component component) { - Either, StorageOperationStatus> componentList - = toscaOperationFacade.getParentComponents(component.getUniqueId()); + Either, StorageOperationStatus> componentList = toscaOperationFacade + .getParentComponents(component.getUniqueId()); if (componentList.isRight()) { return Boolean.FALSE; } - return componentList.left().value().stream() - .flatMap(parentComponent -> parentComponent.getComponentInstancesRelations() - .stream()).flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream()) - .anyMatch(capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation() - .getRequirementUid().equals(requirementDefinition.getUniqueId())); + return componentList.left().value().stream().flatMap(parentComponent -> parentComponent.getComponentInstancesRelations().stream()) + .flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream()).anyMatch( + capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation().getRequirementUid() + .equals(requirementDefinition.getUniqueId())); } } 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 eb4bb33d70..cc10da0a6e 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -26,13 +25,10 @@ import org.springframework.stereotype.Component; @Component("requirementsBusinessLogic") public class RequirementsBusinessLogic { - private static final Logger log = Logger.getLogger(RequirementsBusinessLogic.class); + private static final Logger log = Logger.getLogger(RequirementsBusinessLogic.class); @javax.annotation.Resource private ComponentsUtils componentsUtils; - @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 a3d746da89..22fdc3b6e5 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import static java.util.stream.Collectors.joining; @@ -190,154 +189,143 @@ import org.yaml.snakeyaml.Yaml; @org.springframework.stereotype.Component("resourceBusinessLogic") public class ResourceBusinessLogic extends ComponentBusinessLogic { - private static final String DELETE_RESOURCE = "Delete Resource"; - private static final String IN_RESOURCE = " in resource {} "; - private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; - private static final String INITIAL_VERSION = "0.1"; - private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class); - private static final String CERTIFICATION_ON_IMPORT = "certification on import"; - private static final String CREATE_RESOURCE = "Create Resource"; - private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update"; - private static final String CATEGORY_IS_EMPTY = "Resource category is empty"; - private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate"; - private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name "; - private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} "; - private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName()); - - private IInterfaceLifecycleOperation interfaceTypeOperation; - private LifecycleBusinessLogic lifecycleBusinessLogic; - - private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - private final ResourceImportManager resourceImportManager; - private final InputsBusinessLogic inputsBusinessLogic; - private final OutputsBusinessLogic outputsBusinessLogic; - private final CompositionBusinessLogic compositionBusinessLogic; - private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic; - private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic; - private final MergeInstanceUtils mergeInstanceUtils; - private final UiComponentDataConverter uiComponentDataConverter; - private final CsarBusinessLogic csarBusinessLogic; - private final PropertyBusinessLogic propertyBusinessLogic; - private final PolicyBusinessLogic policyBusinessLogic; - - @Autowired - public ResourceBusinessLogic(final IElementOperation elementDao, - final IGroupOperation groupOperation, - final IGroupInstanceOperation groupInstanceOperation, - final IGroupTypeOperation groupTypeOperation, - final GroupBusinessLogic groupBusinessLogic, - final InterfaceOperation interfaceOperation, - final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - final ArtifactsBusinessLogic artifactsBusinessLogic, - final ComponentInstanceBusinessLogic componentInstanceBusinessLogic, - final @Lazy ResourceImportManager resourceImportManager, - final InputsBusinessLogic inputsBusinessLogic, - final OutputsBusinessLogic outputsBusinessLogic, - final CompositionBusinessLogic compositionBusinessLogic, - final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic, - final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic, - final MergeInstanceUtils mergeInstanceUtils, - final UiComponentDataConverter uiComponentDataConverter, - final CsarBusinessLogic csarBusinessLogic, - final ArtifactsOperations artifactToscaOperation, - final PropertyBusinessLogic propertyBusinessLogic, - final ComponentContactIdValidator componentContactIdValidator, - final ComponentNameValidator componentNameValidator, - final ComponentTagsValidator componentTagsValidator, - final ComponentValidator componentValidator, - final ComponentIconValidator componentIconValidator, - final ComponentProjectCodeValidator componentProjectCodeValidator, - final ComponentDescriptionValidator componentDescriptionValidator, - final PolicyBusinessLogic policyBusinessLogic) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation, - interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, - componentNameValidator, componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, - componentDescriptionValidator); - this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; - this.resourceImportManager = resourceImportManager; - this.inputsBusinessLogic = inputsBusinessLogic; - this.outputsBusinessLogic = outputsBusinessLogic; - this.compositionBusinessLogic = compositionBusinessLogic; - this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic; - this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic; - this.mergeInstanceUtils = mergeInstanceUtils; - this.uiComponentDataConverter = uiComponentDataConverter; - this.csarBusinessLogic = csarBusinessLogic; - this.propertyBusinessLogic = propertyBusinessLogic; - this.policyBusinessLogic = policyBusinessLogic; - } - - @Autowired - private ICapabilityTypeOperation capabilityTypeOperation; - - @Autowired - private TopologyComparator topologyComparator; - - @Autowired - private ComponentValidator componentValidator; - - @Autowired - private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic; - - @Autowired - private SoftwareInformationBusinessLogic softwareInformationBusinessLogic; - - public LifecycleBusinessLogic getLifecycleBusinessLogic() { - return lifecycleBusinessLogic; - } + private static final String DELETE_RESOURCE = "Delete Resource"; + private static final String IN_RESOURCE = " in resource {} "; + private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; + private static final String INITIAL_VERSION = "0.1"; + private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class); + private static final String CERTIFICATION_ON_IMPORT = "certification on import"; + private static final String CREATE_RESOURCE = "Create Resource"; + private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update"; + private static final String CATEGORY_IS_EMPTY = "Resource category is empty"; + private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate"; + private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name "; + private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} "; + private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName()); + private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + private final ResourceImportManager resourceImportManager; + private final InputsBusinessLogic inputsBusinessLogic; + private final OutputsBusinessLogic outputsBusinessLogic; + private final CompositionBusinessLogic compositionBusinessLogic; + private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic; + private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic; + private final MergeInstanceUtils mergeInstanceUtils; + private final UiComponentDataConverter uiComponentDataConverter; + private final CsarBusinessLogic csarBusinessLogic; + private final PropertyBusinessLogic propertyBusinessLogic; + private final PolicyBusinessLogic policyBusinessLogic; + private IInterfaceLifecycleOperation interfaceTypeOperation; + private LifecycleBusinessLogic lifecycleBusinessLogic; + @Autowired + private ICapabilityTypeOperation capabilityTypeOperation; + @Autowired + private TopologyComparator topologyComparator; + @Autowired + private ComponentValidator componentValidator; + @Autowired + private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic; + @Autowired + private SoftwareInformationBusinessLogic softwareInformationBusinessLogic; + + @Autowired + public ResourceBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation, + final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation, + final GroupBusinessLogic groupBusinessLogic, final InterfaceOperation interfaceOperation, + final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + final ArtifactsBusinessLogic artifactsBusinessLogic, + final ComponentInstanceBusinessLogic componentInstanceBusinessLogic, + final @Lazy ResourceImportManager resourceImportManager, final InputsBusinessLogic inputsBusinessLogic, + final OutputsBusinessLogic outputsBusinessLogic, final CompositionBusinessLogic compositionBusinessLogic, + final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic, + final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic, + final MergeInstanceUtils mergeInstanceUtils, final UiComponentDataConverter uiComponentDataConverter, + final CsarBusinessLogic csarBusinessLogic, final ArtifactsOperations artifactToscaOperation, + final PropertyBusinessLogic propertyBusinessLogic, final ComponentContactIdValidator componentContactIdValidator, + final ComponentNameValidator componentNameValidator, final ComponentTagsValidator componentTagsValidator, + final ComponentValidator componentValidator, final ComponentIconValidator componentIconValidator, + final ComponentProjectCodeValidator componentProjectCodeValidator, + final ComponentDescriptionValidator componentDescriptionValidator, final PolicyBusinessLogic policyBusinessLogic) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation, + interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator, + componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); + this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; + this.resourceImportManager = resourceImportManager; + this.inputsBusinessLogic = inputsBusinessLogic; + this.outputsBusinessLogic = outputsBusinessLogic; + this.compositionBusinessLogic = compositionBusinessLogic; + this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic; + this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic; + this.mergeInstanceUtils = mergeInstanceUtils; + this.uiComponentDataConverter = uiComponentDataConverter; + this.csarBusinessLogic = csarBusinessLogic; + this.propertyBusinessLogic = propertyBusinessLogic; + this.policyBusinessLogic = policyBusinessLogic; + } + + static Either rollbackWithEither(final JanusGraphDao janusGraphDao, final ActionStatus actionStatus, + final String... params) { + if (janusGraphDao != null) { + janusGraphDao.rollback(); + } + return Either.right(new ByActionStatusComponentException(actionStatus, params)); + } + + public LifecycleBusinessLogic getLifecycleBusinessLogic() { + return lifecycleBusinessLogic; + } @Autowired public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) { this.lifecycleBusinessLogic = lifecycleBusinessLogic; } - @VisibleForTesting - protected void setComponentValidator(ComponentValidator componentValidator) { - this.componentValidator = componentValidator; - } + @VisibleForTesting + protected void setComponentValidator(ComponentValidator componentValidator) { + this.componentValidator = componentValidator; + } - public IElementOperation getElementDao() { - return elementDao; - } + public IElementOperation getElementDao() { + return elementDao; + } - public void setElementDao(IElementOperation elementDao) { - this.elementDao = elementDao; - } + public void setElementDao(IElementOperation elementDao) { + this.elementDao = elementDao; + } - public UserBusinessLogic getUserAdmin() { - return this.userAdmin; - } + public UserBusinessLogic getUserAdmin() { + return this.userAdmin; + } - @Autowired - @Override - public void setUserAdmin(UserBusinessLogic userAdmin) { - this.userAdmin = userAdmin; - } + @Autowired + @Override + public void setUserAdmin(UserBusinessLogic userAdmin) { + this.userAdmin = userAdmin; + } - public ComponentsUtils getComponentsUtils() { - return this.componentsUtils; - } + public ComponentsUtils getComponentsUtils() { + return this.componentsUtils; + } - @Autowired - @Override - public void setComponentsUtils(ComponentsUtils componentsUtils) { - this.componentsUtils = componentsUtils; - } + @Autowired + @Override + public void setComponentsUtils(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } - public ArtifactsBusinessLogic getArtifactsManager() { - return artifactsBusinessLogic; - } + public ArtifactsBusinessLogic getArtifactsManager() { + return artifactsBusinessLogic; + } - public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { - this.artifactsBusinessLogic = artifactsManager; - } + public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { + this.artifactsBusinessLogic = artifactsManager; + } - public ApplicationDataTypeCache getApplicationDataTypeCache() { - return applicationDataTypeCache; - } + public ApplicationDataTypeCache getApplicationDataTypeCache() { + return applicationDataTypeCache; + } @Autowired - @Override + @Override public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) { this.applicationDataTypeCache = applicationDataTypeCache; } @@ -347,1289 +335,1058 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { this.interfaceTypeOperation = interfaceTypeOperation; } - /** - * 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 List getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, - String userId) { - User user = validateUserExists(userId); - 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()) { - throw new StorageException(getResponse.right() - .value()); - } - - return getResponse.left() - .value(); - } - - public Either, ResponseFormat> validateResourceNameExists(String resourceName, - ResourceTypeEnum resourceTypeEnum, String userId) { - - validateUserExists(userId); - - Either dataModelResponse = toscaOperationFacade - .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); - // DE242223 + /** + * 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 List getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) { + User user = validateUserExists(userId); + 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()) { + throw new StorageException(getResponse.right().value()); + } + return getResponse.left().value(); + } + + public Either, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, + String userId) { + validateUserExists(userId); + Either dataModelResponse = toscaOperationFacade + .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); + // DE242223 janusGraphDao.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 Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map csarUIPayload, + String payloadName) { + validateResourceBeforeCreate(resource, user, false); + String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName; + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Starting to create resource from CSAR by user {} ", user.getUserId()); + if (StringUtils.isNotEmpty(csarUUID)) { + csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID); + log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); + Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID); + return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value(); + } + final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false); + return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value(); + } + + public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map csarUIPayload, String payloadName, + String resourceUniqueId) { + String csarUUID = payloadName; + String csarVersion = null; + Resource updatedResource = null; + if (payloadName == null) { + csarUUID = resource.getCsarUUID(); + csarVersion = resource.getCsarVersion(); + } + if (csarUUID != null && !csarUUID.isEmpty()) { + Resource oldResource = getResourceByUniqueId(resourceUniqueId); + validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user); + validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user); + if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) { + overrideImmutableMetadata(oldResource, resource); + } + validateResourceBeforeCreate(resource, user, false); + String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null; + 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)) { + updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false); + } else { + updatedResource = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, + 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); + throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName()); + } + return updatedResource; + } + + private void validateCsarIsNotAlreadyUsed(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 != resourceLinkedToCsarRes.right().value()) { + log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName()); + throw new StorageException(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); + throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName()); + } + } + + private void validateCsarUuidMatching(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); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID); + } + } + + private Resource getResourceByUniqueId(String resourceUniqueId) { + Either oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId); + if (oldResourceRes.isRight()) { + log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value()); + throw new StorageException(oldResourceRes.right().value()); + } + return oldResourceRes.left().value(); + } + + private void overrideImmutableMetadata(Resource oldResource, Resource resource) { + resource.setName(oldResource.getName()); + resource.setIcon(oldResource.getIcon()); + resource.setTags(oldResource.getTags()); + resource.setCategories(oldResource.getCategories()); + resource.setDerivedFrom(oldResource.getDerivedFrom()); + } - 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 Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user, - Map csarUIPayload, String payloadName) { - validateResourceBeforeCreate(resource, user, false); - String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName; - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId()); - if (StringUtils.isNotEmpty(csarUUID)) { - csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID); - log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); - - Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID); - return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left() - .map(r -> (Resource) r) - .left() - .value(); - } - - final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false); - return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left() - .map(r -> (Resource) r) - .left() - .value(); - } - - public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map csarUIPayload, - String payloadName, String resourceUniqueId) { - String csarUUID = payloadName; - String csarVersion = null; - Resource updatedResource = null; - if (payloadName == null) { - csarUUID = resource.getCsarUUID(); - csarVersion = resource.getCsarVersion(); - } - if (csarUUID != null && !csarUUID.isEmpty()) { - Resource oldResource = getResourceByUniqueId(resourceUniqueId); - validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user); - validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user); - if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) { - overrideImmutableMetadata(oldResource, resource); - } - validateResourceBeforeCreate(resource, user, false); - String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null; - 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)) { - updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false); - } else { - updatedResource = updateResourceFromCsar(oldResource, resource, user, - AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, 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); - throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName()); - } - return updatedResource; - } - - private void validateCsarIsNotAlreadyUsed(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 != resourceLinkedToCsarRes.right().value()) { - log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, - resource.getSystemName()); - throw new StorageException(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); - throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left() - .value() - .getName()); - } - } - - private void validateCsarUuidMatching(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); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, - oldCsarUUID); - } - } - - private Resource getResourceByUniqueId(String resourceUniqueId) { - Either oldResourceRes = toscaOperationFacade - .getToscaFullElement(resourceUniqueId); - if (oldResourceRes.isRight()) { - log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, - oldResourceRes.right() - .value()); - throw new StorageException(oldResourceRes.right() - .value()); - } - return oldResourceRes.left() - .value(); - } - - private void overrideImmutableMetadata(Resource oldResource, Resource resource) { - resource.setName(oldResource.getName()); - resource.setIcon(oldResource.getIcon()); - resource.setTags(oldResource.getTags()); - resource.setCategories(oldResource.getCategories()); - resource.setDerivedFrom(oldResource.getDerivedFrom()); - } - - private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user, - AuditingActionEnum updateResource, boolean inTransaction, Map csarUIPayload, - String csarUUID) { - Resource updatedResource = null; - validateLifecycleState(oldResource, user); - String lockedResourceId = oldResource.getUniqueId(); - List createdArtifacts = new ArrayList<>(); - CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID); - lockComponent(lockedResourceId, oldResource, "update Resource From Csar"); - - Map nodeTypesInfo = csarInfo.extractNodeTypesInfo(); - - Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( - nodeTypesInfo, csarInfo, oldResource); - if (findNodeTypesArtifactsToHandleRes.isRight()) { - log.debug("failed to find node types for update with artifacts during import csar {}. ", - csarInfo.getCsarUUID()); - throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right() - .value()); - } - Map>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes - .left() - .value(); - try { - updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, - csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, - nodeTypesArtifactsToHandle, null, false); - - } catch (ComponentException | StorageException e) { - rollback(inTransaction, newResource, createdArtifacts, null); - throw e; - } - finally { + private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user, AuditingActionEnum updateResource, + boolean inTransaction, Map csarUIPayload, String csarUUID) { + Resource updatedResource = null; + validateLifecycleState(oldResource, user); + String lockedResourceId = oldResource.getUniqueId(); + List createdArtifacts = new ArrayList<>(); + CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID); + lockComponent(lockedResourceId, oldResource, "update Resource From Csar"); + Map nodeTypesInfo = csarInfo.extractNodeTypesInfo(); + Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( + nodeTypesInfo, csarInfo, oldResource); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID()); + throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value()); + } + Map>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left() + .value(); + try { + updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(), + csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false); + } catch (ComponentException | StorageException e) { + rollback(inTransaction, newResource, createdArtifacts, null); + throw e; + } finally { janusGraphDao.commit(); - log.debug("unlock resource {}", lockedResourceId); - graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); - } - return updatedResource; - - } - - private void validateLifecycleState(Resource oldResource, User user) { - if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState() - && !oldResource.getLastUpdaterUserId() - .equals(user.getUserId())) { - log.debug( - "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}", - oldResource.getLastUpdaterUserId(), user.getUserId()); - throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); - } - } - - private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum, - List createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, - Map nodeTypesInfo, - Map>> nodeTypesArtifactsToHandle, - String nodeName, boolean isNested) { - boolean inTransaction = true; - boolean shouldLock = false; - Resource preparedResource = null; - ParsedToscaYamlInfo uploadComponentInstanceInfoMap; - try { - uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, - nodeTypesInfo, csarInfo, nodeName, oldResource); - Map instances = uploadComponentInstanceInfoMap.getInstances(); + log.debug("unlock resource {}", lockedResourceId); + graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); + } + return updatedResource; + } + + private void validateLifecycleState(Resource oldResource, User user) { + if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState() && !oldResource.getLastUpdaterUserId() + .equals(user.getUserId())) { + log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}", + oldResource.getLastUpdaterUserId(), user.getUserId()); + throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); + } + } + + private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum, + List createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, + Map nodeTypesInfo, + Map>> nodeTypesArtifactsToHandle, + String nodeName, boolean isNested) { + boolean inTransaction = true; + boolean shouldLock = false; + Resource preparedResource = null; + ParsedToscaYamlInfo uploadComponentInstanceInfoMap; + try { + uploadComponentInstanceInfoMap = csarBusinessLogic + .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldResource); + Map instances = uploadComponentInstanceInfoMap.getInstances(); if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) { throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName); } - preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(), - inTransaction, shouldLock, isNested).left; - log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); - handleResourceGenericType(preparedResource); - handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, - createdArtifacts, nodeTypesInfo, csarInfo, nodeName); - preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs()); - Map existingNodeTypesByResourceNames = new HashMap<>(); - preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames); - preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames); - } catch (ComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat() == null - ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); - log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, - responseFormat); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), - preparedResource == null ? oldResource : preparedResource, actionEnum); - throw e; - } catch (StorageException e) { - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); - log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, - responseFormat); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), - preparedResource == null ? oldResource : preparedResource, actionEnum); - throw e; - } - Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic - .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), - preparedResource.getSystemName()); - if (validateUpdateVfGroupNamesRes.isRight()) { - - throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right() - .value()); - } - // add groups to newResource - Map groups; - - if (!validateUpdateVfGroupNamesRes.left() - .value() - .isEmpty()) { - groups = validateUpdateVfGroupNamesRes.left() - .value(); - } else { - groups = uploadComponentInstanceInfoMap.getGroups(); - } - handleGroupsProperties(preparedResource, groups); - Either isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource); - - preparedResource = updateGroupsOnResource(preparedResource, groups); - - 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()); - throw new ByResponseFormatComponentException(updateArtifactsEither.right() - .value()); - } - preparedResource = getResourceWithGroups(updateArtifactsEither.left() - .value() - .getUniqueId()); - - updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value()); - updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value()); - - final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : ""; - preparedResource = getResourceWithGroups(preparedResourceId); - - updateVolumeGroup(preparedResource); - - ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource); - if (mergingPropsAndInputsStatus != ActionStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, - preparedResource); - throw new ByResponseFormatComponentException(responseFormat); - } - compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier() - .getUserId()); - return preparedResource; - } - - protected void updateVolumeGroup(Resource preparedResource) { - List groups = preparedResource.safeGetGroups(); - for (GroupDefinition group : groups) { - Map createdNewArtifacts = preparedResource.getDeploymentArtifacts(); - if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) { - List volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList()); - if (!volumePropList.isEmpty()) { - PropertyDataDefinition volumeProp = volumePropList.get(0); - if (volumeProp != null) { - boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values())); - - if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) { - volumeProp.setValue(String.valueOf(isVolumeGroup)); - volumeProp.setDefaultValue(String.valueOf(isVolumeGroup)); - } - } - } - } - } - } - - private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) { - if (oldResource == null || preparedResource == null) { - log.debug("Failed to update groups name : oldResource or preparedResource is null"); - } else if (CollectionUtils.isNotEmpty(oldResource.getGroups()) - && CollectionUtils.isNotEmpty(preparedResource.getGroups())) { - Map oldGroups = oldResource.getGroups() - .stream() - .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName)); - - List updatedGroups = preparedResource.getGroups() - .stream() - .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName() - .equals(oldGroups.get(group.getInvariantName()))) - .collect(toList()); - - if (CollectionUtils.isNotEmpty(updatedGroups)) { - if (isTopologyChanged) { - updatedGroups.stream().filter(group -> !group.isVspOriginated()) - .forEach(group -> group.setName(oldGroups.get(group.getInvariantName()))); - } else { - updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName()))); - } - groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false); - } - } - } - - private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource, - boolean isTopologyChanged) { - if (oldResource == null || preparedResource == null) { - log.debug("Failed to update resource instances names : oldResource or preparedResource is null"); - } else { - if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) { - Map oldInstances = oldResource.getComponentInstances() - .stream() - .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName)); - List updatedInstances = preparedResource.getComponentInstances() - .stream() - .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName() - .equals(oldInstances.get(i.getInvariantName()))) - .collect(toList()); - if (CollectionUtils.isNotEmpty(updatedInstances)) { - if (isTopologyChanged) { - updatedInstances.stream().filter(i -> !i.isCreatedFromCsar()) - .forEach(i -> i.setName(oldInstances.get(i.getInvariantName()))); - } else { - updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName()))); - } - } - } - - componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, - null, preparedResource.getUniqueId(), csarInfo.getModifier() - .getUserId(), - preparedResource.getComponentInstances(), false); - } - } - - 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, - 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 Resource handleResourceGenericType(Resource resource) { - Resource genericResource = fetchAndSetDerivedFromGenericType(resource); - if (resource.shouldGenerateInputs()) { - generateAndAddInputsFromGenericTypeProperties(resource, genericResource); - } - return genericResource; - } - - private Either>>, ResponseFormat> findNodeTypesArtifactsToHandle( - final Map nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) { - - final Map>> nodeTypesArtifactsToHandle = new HashMap<>(); - Either>>, ResponseFormat> - nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); - - try { - final Map> extractedVfcsArtifacts = CsarUtils - .extractVfcsArtifactsFromCsar(csarInfo.getCsar()); - final Map> extractedVfcToscaNames = extractVfcToscaNames( - nodeTypesInfo, oldResource.getName(), csarInfo); - log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", - oldResource.getName(), csarInfo.getCsarUUID()); - extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, - nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames)); - } catch (Exception e) { - final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - nodeTypesArtifactsToHandleRes = Either.right(responseFormat); - log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); - } - return nodeTypesArtifactsToHandleRes; - } - - private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, - Map>> nodeTypesArtifactsToHandle, - Resource resource, Map> extractedVfcsArtifacts, String namespace, - ImmutablePair vfcToscaNames) { - - EnumMap> curNodeTypeArtifactsToHandle = null; - log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft()); - Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), - null); - if (!isEmpty(extractedVfcsArtifacts)) { - List currArtifacts = new ArrayList<>(); - if (extractedVfcsArtifacts.containsKey(namespace)) { - handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace)); - } - curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); - } 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(toList())); - // delete all deployment artifacts - artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts() - .values()); - if (!artifactsToDelete.isEmpty()) { - curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); - } - } - if (isNotEmpty(curNodeTypeArtifactsToHandle)) { - nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle); - } - } - - private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, - String previousVfcToscaName, StorageOperationStatus status) { - if (status != null && status != StorageOperationStatus.NOT_FOUND) { - log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName, - status); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, - AuditingActionEnum.CREATE_RESOURCE); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); - } else if (StringUtils.isNotEmpty(currVfcToscaName)) { - return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName) - .left() - .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st)); - } - return null; - } - - private EnumMap> findNodeTypeArtifactsToHandle(Resource curNodeType, - List extractedArtifacts) { - - try { - List artifactsToUpload = new ArrayList<>(extractedArtifacts); - List artifactsToUpdate = new ArrayList<>(); - List artifactsToDelete = new ArrayList<>(); - processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, - artifactsToDelete, collectExistingArtifacts(curNodeType)); - return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete); - } catch (Exception e) { - log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); - throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); - } - } - - private EnumMap> putFoundArtifacts( - List artifactsToUpload, List artifactsToUpdate, - List artifactsToDelete) { - EnumMap> nodeTypeArtifactsToHandle = null; - 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); - } - } - return nodeTypeArtifactsToHandle; - } - - private void processExistingNodeTypeArtifacts(List extractedArtifacts, - List artifactsToUpload, List artifactsToUpdate, - List artifactsToDelete, Map existingArtifacts) { - if (!existingArtifacts.isEmpty()) { - extractedArtifacts.stream() - .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a)); - artifactsToDelete.addAll(existingArtifacts.values()); - } - } - - private void processNodeTypeArtifact(List artifactsToUpload, - List artifactsToUpdate, Map existingArtifacts, - ArtifactDefinition currNewArtifact) { - Optional foundArtifact = existingArtifacts.values() - .stream() - .filter(a -> a.getArtifactName() - .equals(currNewArtifact.getArtifactName())) - .findFirst(); - if (foundArtifact.isPresent()) { - if (foundArtifact.get() - .getArtifactType() - .equals(currNewArtifact.getArtifactType())) { - updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get()); - existingArtifacts.remove(foundArtifact.get() - .getArtifactLabel()); - artifactsToUpload.remove(currNewArtifact); - } else { - log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); - throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, - currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get() - .getArtifactType()); - } - } - } - - private void updateFoundArtifact(List artifactsToUpdate, ArtifactDefinition currNewArtifact, - ArtifactDefinition foundArtifact) { - 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); - } - } - - private Map collectExistingArtifacts(Resource curNodeType) { - Map existingArtifacts = new HashMap<>(); - if (curNodeType == null) { - return existingArtifacts; - } - if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) { - existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); - } - if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) { - existingArtifacts.putAll(curNodeType.getArtifacts() - .entrySet() - .stream() - .filter(e -> e.getValue() - .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))); - } - return existingArtifacts; - } - - /** - * 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 occurred 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) { - List 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, new ArtifactOperationInfo(false, - ignoreLifecycleState, curOperation), - false, inTransaction); - if (ArtifactOperationEnum.isCreateOrLink(curOperation)) { - createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes); - } - handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes); - } - } - if (handleNodeTypeArtifactsRes == null) { - handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleNodeTypeArtifactsRes = Either.right(responseFormat); - log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e); - } - return handleNodeTypeArtifactsRes; - } - - private Map> extractVfcToscaNames(final Map nodeTypesInfo, - final String vfResourceName, - final CsarInfo csarInfo) { - final Map> vfcToscaNames = new HashMap<>(); - - final Map nodes = extractAllNodes(nodeTypesInfo, csarInfo); - if (!nodes.isEmpty()) { - final Iterator> nodesNameEntry = nodes.entrySet().iterator(); - while (nodesNameEntry.hasNext()) { - final Entry nodeType = nodesNameEntry.next(); - final ImmutablePair toscaResourceName = buildNestedToscaResourceName( - ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); - vfcToscaNames.put(nodeType.getKey(), toscaResourceName); - } - } - for (final 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, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); - if (eitherNodeTypes.isLeft()) { - nodes.putAll(eitherNodeTypes.left() - .value()); - } - } - - public Resource createResourceFromCsar(Resource resource, User user, Map csarUIPayload, - String csarUUID) { - log.trace("************* created successfully from YAML, resource TOSCA "); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() ); - CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID); - Map nodeTypesInfo = csarInfo.extractNodeTypesInfo(); - 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()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value()); - throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value()); - } - Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), - csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left() - .value(), - true, false, null); - log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", - vfResource.getToscaResourceName()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() ); - return vfResource; - } - - private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) { - log.trace("validating resource before create"); - user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false)); - // validate user role - validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null); - // VF / PNF "derivedFrom" should be null (or ignored) - if (ModelConverter.isAtomicComponent(resource)) { - validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE); - } - return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null); - - } - - // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, - // nodeTypesArtifactsToCreate, true, false, null - private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName, - Map nodeTypesInfo, CsarInfo csarInfo, - Map>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { - - List createdArtifacts = new ArrayList<>(); - Resource createdResource; - try { - ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource); + preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(), inTransaction, shouldLock, + isNested).left; + log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); + handleResourceGenericType(preparedResource); + handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, + csarInfo, nodeName); + preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs()); + Map existingNodeTypesByResourceNames = new HashMap<>(); + preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), + existingNodeTypesByResourceNames); + preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, + existingNodeTypesByResourceNames); + } catch (ComponentException e) { + ResponseFormat responseFormat = + e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); + log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, responseFormat); + componentsUtils + .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum); + throw e; + } catch (StorageException e) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, responseFormat); + componentsUtils + .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum); + throw e; + } + Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic + .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName()); + if (validateUpdateVfGroupNamesRes.isRight()) { + throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value()); + } + // add groups to newResource + Map groups; + if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { + groups = validateUpdateVfGroupNamesRes.left().value(); + } else { + groups = uploadComponentInstanceInfoMap.getGroups(); + } + handleGroupsProperties(preparedResource, groups); + Either isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource); + preparedResource = updateGroupsOnResource(preparedResource, groups); + 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()); + throw new ByResponseFormatComponentException(updateArtifactsEither.right().value()); + } + preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId()); + updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value()); + updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value()); + final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : ""; + preparedResource = getResourceWithGroups(preparedResourceId); + updateVolumeGroup(preparedResource); + ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource); + if (mergingPropsAndInputsStatus != ActionStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource); + throw new ByResponseFormatComponentException(responseFormat); + } + compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); + return preparedResource; + } + + protected void updateVolumeGroup(Resource preparedResource) { + List groups = preparedResource.safeGetGroups(); + for (GroupDefinition group : groups) { + Map createdNewArtifacts = preparedResource.getDeploymentArtifacts(); + if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) { + List volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())) + .collect(Collectors.toList()); + if (!volumePropList.isEmpty()) { + PropertyDataDefinition volumeProp = volumePropList.get(0); + if (volumeProp != null) { + boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values())); + if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) { + volumeProp.setValue(String.valueOf(isVolumeGroup)); + volumeProp.setDefaultValue(String.valueOf(isVolumeGroup)); + } + } + } + } + } + } + + private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) { + if (oldResource == null || preparedResource == null) { + log.debug("Failed to update groups name : oldResource or preparedResource is null"); + } else if (CollectionUtils.isNotEmpty(oldResource.getGroups()) && CollectionUtils.isNotEmpty(preparedResource.getGroups())) { + Map oldGroups = oldResource.getGroups().stream() + .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName)); + List updatedGroups = preparedResource.getGroups().stream() + .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName().equals(oldGroups.get(group.getInvariantName()))) + .collect(toList()); + if (CollectionUtils.isNotEmpty(updatedGroups)) { + if (isTopologyChanged) { + updatedGroups.stream().filter(group -> !group.isVspOriginated()) + .forEach(group -> group.setName(oldGroups.get(group.getInvariantName()))); + } else { + updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName()))); + } + groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false); + } + } + } + + private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource, boolean isTopologyChanged) { + if (oldResource == null || preparedResource == null) { + log.debug("Failed to update resource instances names : oldResource or preparedResource is null"); + } else { + if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) { + Map oldInstances = oldResource.getComponentInstances().stream() + .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName)); + List updatedInstances = preparedResource.getComponentInstances().stream() + .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName().equals(oldInstances.get(i.getInvariantName()))) + .collect(toList()); + if (CollectionUtils.isNotEmpty(updatedInstances)) { + if (isTopologyChanged) { + updatedInstances.stream().filter(i -> !i.isCreatedFromCsar()).forEach(i -> i.setName(oldInstances.get(i.getInvariantName()))); + } else { + updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName()))); + } + } + } + componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, null, preparedResource.getUniqueId(), + csarInfo.getModifier().getUserId(), preparedResource.getComponentInstances(), false); + } + } + + 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, + 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 Resource handleResourceGenericType(Resource resource) { + Resource genericResource = fetchAndSetDerivedFromGenericType(resource); + if (resource.shouldGenerateInputs()) { + generateAndAddInputsFromGenericTypeProperties(resource, genericResource); + } + return genericResource; + } + + private Either>>, ResponseFormat> findNodeTypesArtifactsToHandle( + final Map nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) { + final Map>> nodeTypesArtifactsToHandle = new HashMap<>(); + Either>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either + .left(nodeTypesArtifactsToHandle); + try { + final Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar()); + final Map> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), + csarInfo); + log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), + csarInfo.getCsarUUID()); + extractedVfcToscaNames.forEach( + (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource, + extractedVfcsArtifacts, namespace, vfcToscaNames)); + } catch (Exception e) { + final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + nodeTypesArtifactsToHandleRes = Either.right(responseFormat); + log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); + } + return nodeTypesArtifactsToHandleRes; + } + + private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, + Map>> nodeTypesArtifactsToHandle, + Resource resource, Map> extractedVfcsArtifacts, String namespace, + ImmutablePair vfcToscaNames) { + EnumMap> curNodeTypeArtifactsToHandle = null; + log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft()); + Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null); + if (!isEmpty(extractedVfcsArtifacts)) { + List currArtifacts = new ArrayList<>(); + if (extractedVfcsArtifacts.containsKey(namespace)) { + handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace)); + } + curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); + } 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(toList())); + // delete all deployment artifacts + artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values()); + if (!artifactsToDelete.isEmpty()) { + curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + } + if (isNotEmpty(curNodeTypeArtifactsToHandle)) { + nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle); + } + } + + private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, + StorageOperationStatus status) { + if (status != null && status != StorageOperationStatus.NOT_FOUND) { + log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName, status); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); + } else if (StringUtils.isNotEmpty(currVfcToscaName)) { + return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName).left() + .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st)); + } + return null; + } + + private EnumMap> findNodeTypeArtifactsToHandle(Resource curNodeType, + List extractedArtifacts) { + try { + List artifactsToUpload = new ArrayList<>(extractedArtifacts); + List artifactsToUpdate = new ArrayList<>(); + List artifactsToDelete = new ArrayList<>(); + processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete, + collectExistingArtifacts(curNodeType)); + return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete); + } catch (Exception e) { + log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); + } + } + + private EnumMap> putFoundArtifacts(List artifactsToUpload, + List artifactsToUpdate, + List artifactsToDelete) { + EnumMap> nodeTypeArtifactsToHandle = null; + 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); + } + } + return nodeTypeArtifactsToHandle; + } + + private void processExistingNodeTypeArtifacts(List extractedArtifacts, List artifactsToUpload, + List artifactsToUpdate, List artifactsToDelete, + Map existingArtifacts) { + if (!existingArtifacts.isEmpty()) { + extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a)); + artifactsToDelete.addAll(existingArtifacts.values()); + } + } + + private void processNodeTypeArtifact(List artifactsToUpload, List artifactsToUpdate, + Map existingArtifacts, ArtifactDefinition currNewArtifact) { + Optional foundArtifact = existingArtifacts.values().stream() + .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst(); + if (foundArtifact.isPresent()) { + if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) { + updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get()); + existingArtifacts.remove(foundArtifact.get().getArtifactLabel()); + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); + throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, + currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType()); + } + } + } + + private void updateFoundArtifact(List artifactsToUpdate, ArtifactDefinition currNewArtifact, + ArtifactDefinition foundArtifact) { + 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); + } + } + + private Map collectExistingArtifacts(Resource curNodeType) { + Map existingArtifacts = new HashMap<>(); + if (curNodeType == null) { + return existingArtifacts; + } + if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) { + existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); + } + if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) { + existingArtifacts.putAll( + curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))); + } + return existingArtifacts; + } + + /** + * 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 occurred 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) { + List 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, + new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction); + if (ArtifactOperationEnum.isCreateOrLink(curOperation)) { + createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes); + } + handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes); + } + } + if (handleNodeTypeArtifactsRes == null) { + handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleNodeTypeArtifactsRes = Either.right(responseFormat); + log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e); + } + return handleNodeTypeArtifactsRes; + } + + private Map> extractVfcToscaNames(final Map nodeTypesInfo, + final String vfResourceName, final CsarInfo csarInfo) { + final Map> vfcToscaNames = new HashMap<>(); + final Map nodes = extractAllNodes(nodeTypesInfo, csarInfo); + if (!nodes.isEmpty()) { + final Iterator> nodesNameEntry = nodes.entrySet().iterator(); + while (nodesNameEntry.hasNext()) { + final Entry nodeType = nodesNameEntry.next(); + final ImmutablePair toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName, + nodeType.getKey()); + vfcToscaNames.put(nodeType.getKey(), toscaResourceName); + } + } + for (final 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, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); + if (eitherNodeTypes.isLeft()) { + nodes.putAll(eitherNodeTypes.left().value()); + } + } + + public Resource createResourceFromCsar(Resource resource, User user, Map csarUIPayload, String csarUUID) { + log.trace("************* created successfully from YAML, resource TOSCA "); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.STARTED, "Starting to create Resource From Csar by user {}", + user.getUserId()); + CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID); + Map nodeTypesInfo = csarInfo.extractNodeTypesInfo(); + 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()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "error: {}", findNodeTypesArtifactsToHandleRes.right().value()); + throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value()); + } + Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo, + csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null); + log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.COMPLETE, "Ended create Resource From Csar by user {}", + user.getUserId()); + return vfResource; + } + + private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) { + log.trace("validating resource before create"); + user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false)); + // validate user role + validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null); + // VF / PNF "derivedFrom" should be null (or ignored) + if (ModelConverter.isAtomicComponent(resource)) { + validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE); + } + return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null); + } + + private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName, Map nodeTypesInfo, + CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { + List createdArtifacts = new ArrayList<>(); + Resource createdResource; + try { + ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic + .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource); if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) { throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } - log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), - StatusCode.STARTED,""); - createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, - AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo, - csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); - log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), - StatusCode.COMPLETE,"The resource has been created: {}",resource.getName()); - } catch (ComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat() == null - ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, - AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } catch (StorageException e) { - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, - AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } - return createdResource; - - } - - public Map createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, - Map mappedToscaTemplate, boolean needLock, - Map>> nodeTypesArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, - CsarInfo csarInfo) { - - Either toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, - TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); - if (toscaVersion.isRight()) { - throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE); - } - Map mapToConvert = new HashMap<>(); - mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left() - .value()); - Map nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate); - createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, mapToConvert, nodeTypes); - return csarInfo.getCreatedNodes(); - } - - private Map getNodeTypesFromTemplate(Map mappedToscaTemplate) { - return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES) - .left() - .orValue(HashMap::new); - } - - private void createNodeTypes(String yamlName, Resource resource, boolean needLock, - Map>> nodeTypesArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, - CsarInfo csarInfo, Map mapToConvert, Map nodeTypes) { - Iterator> nodesNameValueIter = nodeTypes.entrySet() - .iterator(); - Resource vfcCreated = null; - while (nodesNameValueIter.hasNext()) { - Entry nodeType = nodesNameValueIter.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()); - vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeType.getKey()); - log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); - } else if (csarInfo.getCreatedNodesToscaResourceNames() != null - && !csarInfo.getCreatedNodesToscaResourceNames() - .containsKey(nodeType.getKey())) { - log.trace("************* Going to create node {}", nodeType.getKey()); - ImmutablePair resourceCreated = createNodeTypeResourceFromYaml(yamlName, - nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, - nodeTypesNewCreatedArtifacts, true, csarInfo, true); - log.debug("************* Finished to create node {}", nodeType.getKey()); - - vfcCreated = resourceCreated.getLeft(); - csarInfo.getCreatedNodesToscaResourceNames() - .put(nodeType.getKey(), vfcCreated.getToscaResourceName()); - } - if (vfcCreated != null) { - csarInfo.getCreatedNodes() - .put(nodeType.getKey(), vfcCreated); - } - mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()); - } - } - - private Resource handleNestedVfc(Resource resource, - Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName) { - - String yamlName = nodesInfo.get(nodeName) - .getTemplateFileName(); - Map nestedVfcJsonMap = nodesInfo.get(nodeName) - .getMappedToscaTemplate(); - - log.debug("************* Going to create node types from yaml {}", yamlName); - createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, - createdArtifacts, Collections.emptyMap(), csarInfo); - log.debug("************* Finished to create node types from yaml {}", yamlName); - - if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { - log.debug("************* Going to handle complex VFC from yaml {}", yamlName); - resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, - nodeName, yamlName); - } - return resource; - } - - private Resource handleComplexVfc(final Resource resource, - final Map>> - nodesArtifactsToHandle, - final List - createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - final String nodeName, final String yamlName) { - - Resource oldComplexVfc = null; - Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); - 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()); - throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); - } else if (oldComplexVfcRes.isLeft()) { - log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); - final Either eitherValidation = validateNestedDerivedFromDuringUpdate( - oldComplexVfcRes.left().value(), - newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); - if (eitherValidation.isLeft()) { - oldComplexVfc = oldComplexVfcRes.left().value(); - } - } - newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, - yamlName, oldComplexVfc, newComplexVfc); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); - final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, - LifecycleChanceActionEnum.CREATE_FROM_CSAR); - log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); - final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, - lifecycleChangeInfo, true, false, true); - csarInfo.getCreatedNodes().put(nodeName, result); - csarInfo.removeNodeFromQueue(); - return result; - } - - private Resource handleComplexVfc( - Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { - - Resource handleComplexVfcRes; - Map mappedToscaTemplate = nodesInfo.get(nodeName) - .getMappedToscaTemplate(); - String yamlContent = new String(csarInfo.getCsar() - .get(yamlName)); - Map newNodeTypesInfo = nodesInfo.entrySet() - .stream() - .collect(toMap(Entry::getKey, e -> e.getValue() - .getUnmarkedCopy())); - CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); - if (oldComplexVfc == null) { - handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, - csarInfo, nodesArtifactsToHandle, false, true, nodeName); - } else { - handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, - AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo, - newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); - } - return handleComplexVfcRes; - } - - private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, - Map nodesInfo) { - - Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); - log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); - csarInfo.addNodeToQueue(nodeName); - return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, - true, csarInfo); - } - - private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) { - - final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length()); - final String[] findTypes = nameWithouNamespacePrefix.split("\\."); - - if(findTypes.length > 1){ - final String resourceType = findTypes[0]; - return nameWithouNamespacePrefix.substring(resourceType.length()); - } - return nameWithouNamespacePrefix; - } - - private ImmutablePair createNodeTypeResourceFromYaml(final String yamlName, - final Entry nodeNameValue, - User user, - final Map mapToConvert, - final Resource resourceVf, - final boolean needLock, - final Map> nodeTypeArtifactsToHandle, - final List nodeTypesNewCreatedArtifacts, - final boolean forceCertificationAllowed, - final CsarInfo csarInfo, - final boolean isNested) { - - final UploadResourceInfo resourceMetaData = fillResourceMetadata( - yamlName, resourceVf, nodeNameValue.getKey(), user); - - final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo); - user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); - return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, - nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, - nodeNameValue.getKey(), isNested); - } - - private String buildNodeTypeYaml(final Entry nodeNameValue, - final Map mapToConvert, - final String nodeResourceType, - final 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. - final DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - final Yaml yaml = new Yaml(options); - - final Map node = new HashMap<>(); - node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()) - .getLeft(), nodeNameValue.getValue()); - mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); - - return yaml.dumpAsMap(mapToConvert); - } - - public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) { - validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); - return true; - } - - public ImmutablePair 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 -> validateResourceCreationFromNodeType( - resource, creator); - return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, - lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, - nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); - } - - /** - * Validates if a given node type name has a valid prefix. - * - * @param nodeName node name from definition file - * @param definedResourceNamespaceList is a list of all node type name prefix allowed - * @return a valid node type name prefix if it`s found - */ - public Optional validateNodeTypeNamePrefix(final String nodeName, - final List definedResourceNamespaceList) { - for (final String validNamespace : definedResourceNamespaceList) { - if (nodeName.startsWith(validNamespace)) { - return Optional.of(validNamespace); - } - } - return Optional.empty(); - } - - private List getDefinedNodeTypeNamespaceList() { - return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace(); - } - - private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf, - final String nodeName, final User user) { - - final UploadResourceInfo resourceMetaData = new UploadResourceInfo(); - - final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName); - log.debug("Node type Name prefix {}", nodeTypeNamePrefix); - - if (!nodeName.startsWith(nodeTypeNamePrefix)) { - log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList()); - throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, - resourceMetaData.getName(), nodeName); - } - - final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix); - final String namePrefix = nodeName.replace(actualName, ""); - String resourceType = namePrefix.substring(nodeTypeNamePrefix.length()); - log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix, - resourceType, nodeName, actualName, nodeTypeNamePrefix); - - // 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(); - } - - if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) { - 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()); - throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, - resourceMetaData.getName(), nodeName); - } - - // Setting name - resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString()); - - // Setting type from name - final 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 - final List tags = new ArrayList<>(); - tags.add(resourceMetaData.getName()); - resourceMetaData.setTags(tags); - - // Setting category - final CategoryDefinition category = new CategoryDefinition(); - category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); - final SubCategoryDefinition subCategory = new SubCategoryDefinition(); - subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); - category.addSubCategory(subCategory); - final List categories = new ArrayList<>(); - categories.add(category); - resourceMetaData.setCategories(categories); - - return resourceMetaData; - } - - private Resource buildComplexVfcMetadata(final Resource resourceVf, - final CsarInfo csarInfo, - final String nodeName, - final Map nodesInfo) { - final Resource cvfc = new Resource(); - final 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()); - - final List tags = new ArrayList<>(); - tags.add(cvfc.getName()); - cvfc.setTags(tags); - - final CategoryDefinition category = new CategoryDefinition(); - category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); - SubCategoryDefinition subCategory = new SubCategoryDefinition(); - subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); - category.addSubCategory(subCategory); - final 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(final String resourceVfName, final 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 Resource createResourceAndRIsFromYaml(final String yamlName, - Resource resource, - final ParsedToscaYamlInfo parsedToscaYamlInfo, - final AuditingActionEnum actionEnum, - final boolean isNormative, - final List createdArtifacts, - final String topologyTemplateYaml, - final Map nodeTypesInfo, - final CsarInfo csarInfo, - final Map>> nodeTypesArtifactsToCreate, - final boolean shouldLock, - final boolean inTransaction, - final String nodeName) { - - final List nodeTypesNewCreatedArtifacts = new ArrayList<>(); + log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, ""); + createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, + createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); + log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "The resource has been created: {}", resource.getName()); + } catch (ComponentException e) { + ResponseFormat responseFormat = + e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + throw e; + } catch (StorageException e) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + throw e; + } + return createdResource; + } + + public Map createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map mappedToscaTemplate, + boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, + Map nodeTypesInfo, CsarInfo csarInfo) { + Either toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); + if (toscaVersion.isRight()) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE); + } + Map mapToConvert = new HashMap<>(); + mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value()); + Map nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate); + createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, + nodeTypes); + return csarInfo.getCreatedNodes(); + } + + private Map getNodeTypesFromTemplate(Map mappedToscaTemplate) { + return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new); + } + + private void createNodeTypes(String yamlName, Resource resource, boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, CsarInfo csarInfo, + Map mapToConvert, Map nodeTypes) { + Iterator> nodesNameValueIter = nodeTypes.entrySet().iterator(); + Resource vfcCreated = null; + while (nodesNameValueIter.hasNext()) { + Entry nodeType = nodesNameValueIter.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()); + vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeType.getKey()); + log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); + } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames() + .containsKey(nodeType.getKey())) { + log.trace("************* Going to create node {}", nodeType.getKey()); + ImmutablePair resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), + mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true); + log.debug("************* Finished to create node {}", nodeType.getKey()); + vfcCreated = resourceCreated.getLeft(); + csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName()); + } + if (vfcCreated != null) { + csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); + } + mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()); + } + } + + private Resource handleNestedVfc(Resource resource, Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName) { + String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); + Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); + log.debug("************* Going to create node types from yaml {}", yamlName); + createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, + Collections.emptyMap(), csarInfo); + log.debug("************* Finished to create node types from yaml {}", yamlName); + if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { + log.debug("************* Going to handle complex VFC from yaml {}", yamlName); + resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName); + } + return resource; + } + + private Resource handleComplexVfc(final Resource resource, + final Map>> nodesArtifactsToHandle, + final List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + final String nodeName, final String yamlName) { + Resource oldComplexVfc = null; + Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); + 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()); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); + } else if (oldComplexVfcRes.isLeft()) { + log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); + final Either eitherValidation = validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), + newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); + if (eitherValidation.isLeft()) { + oldComplexVfc = oldComplexVfcRes.left().value(); + } + } + newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, + newComplexVfc); + csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); + final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, + LifecycleChanceActionEnum.CREATE_FROM_CSAR); + log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); + final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true); + csarInfo.getCreatedNodes().put(nodeName, result); + csarInfo.removeNodeFromQueue(); + return result; + } + + private Resource handleComplexVfc(Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { + Resource handleComplexVfcRes; + Map mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate(); + String yamlContent = new String(csarInfo.getCsar().get(yamlName)); + Map newNodeTypesInfo = nodesInfo.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy())); + CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); + if (oldComplexVfc == null) { + handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle, + false, true, nodeName); + } else { + handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, + yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); + } + return handleComplexVfcRes; + } + + private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map nodesInfo) { + Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); + log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); + csarInfo.addNodeToQueue(nodeName); + return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); + } + + private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) { + final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length()); + final String[] findTypes = nameWithouNamespacePrefix.split("\\."); + if (findTypes.length > 1) { + final String resourceType = findTypes[0]; + return nameWithouNamespacePrefix.substring(resourceType.length()); + } + return nameWithouNamespacePrefix; + } + + private ImmutablePair createNodeTypeResourceFromYaml(final String yamlName, final Entry nodeNameValue, + User user, final Map mapToConvert, + final Resource resourceVf, final boolean needLock, + final Map> nodeTypeArtifactsToHandle, + final List nodeTypesNewCreatedArtifacts, + final boolean forceCertificationAllowed, final CsarInfo csarInfo, + final boolean isNested) { + final UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); + final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo); + user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); + return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle, + nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested); + } + + private String buildNodeTypeYaml(final Entry nodeNameValue, final Map mapToConvert, final String nodeResourceType, + final 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. + final DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + final Yaml yaml = new Yaml(options); + final Map node = new HashMap<>(); + node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(), + nodeNameValue.getValue()); + mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); + return yaml.dumpAsMap(mapToConvert); + } + + public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) { + validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); + return true; + } + + public ImmutablePair 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 -> validateResourceCreationFromNodeType(resource, creator); + return resourceImportManager + .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, + nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); + } + + /** + * Validates if a given node type name has a valid prefix. + * + * @param nodeName node name from definition file + * @param definedResourceNamespaceList is a list of all node type name prefix allowed + * @return a valid node type name prefix if it`s found + */ + public Optional validateNodeTypeNamePrefix(final String nodeName, final List definedResourceNamespaceList) { + for (final String validNamespace : definedResourceNamespaceList) { + if (nodeName.startsWith(validNamespace)) { + return Optional.of(validNamespace); + } + } + return Optional.empty(); + } + + private List getDefinedNodeTypeNamespaceList() { + return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace(); + } + + private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf, final String nodeName, final User user) { + final UploadResourceInfo resourceMetaData = new UploadResourceInfo(); + final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName); + log.debug("Node type Name prefix {}", nodeTypeNamePrefix); + if (!nodeName.startsWith(nodeTypeNamePrefix)) { + log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); + } + final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix); + final String namePrefix = nodeName.replace(actualName, ""); + String resourceType = namePrefix.substring(nodeTypeNamePrefix.length()); + log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix, resourceType, nodeName, actualName, + nodeTypeNamePrefix); + // 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(); + } + if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) { + 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()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); + } + // Setting name + resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString()); + // Setting type from name + final 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 + final List tags = new ArrayList<>(); + tags.add(resourceMetaData.getName()); + resourceMetaData.setTags(tags); + // Setting category + final CategoryDefinition category = new CategoryDefinition(); + category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); + final SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); + category.addSubCategory(subCategory); + final List categories = new ArrayList<>(); + categories.add(category); + resourceMetaData.setCategories(categories); + return resourceMetaData; + } + + private Resource buildComplexVfcMetadata(final Resource resourceVf, final CsarInfo csarInfo, final String nodeName, + final Map nodesInfo) { + final Resource cvfc = new Resource(); + final 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()); + final List tags = new ArrayList<>(); + tags.add(cvfc.getName()); + cvfc.setTags(tags); + final CategoryDefinition category = new CategoryDefinition(); + category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); + category.addSubCategory(subCategory); + final 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(final String resourceVfName, final 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 Resource createResourceAndRIsFromYaml(final String yamlName, Resource resource, final ParsedToscaYamlInfo parsedToscaYamlInfo, + final AuditingActionEnum actionEnum, final boolean isNormative, + final List createdArtifacts, final String topologyTemplateYaml, + final Map nodeTypesInfo, final CsarInfo csarInfo, + final Map>> nodeTypesArtifactsToCreate, + final boolean shouldLock, final boolean inTransaction, final String nodeName) { + final List nodeTypesNewCreatedArtifacts = new ArrayList<>(); if (shouldLock) { - final Either lockResult = lockComponentByName(resource.getSystemName(), resource, - CREATE_RESOURCE); + final Either lockResult = lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE); if (lockResult.isRight()) { rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ByResponseFormatComponentException(lockResult.right().value()); @@ -1638,48 +1395,44 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } try { log.trace("************* createResourceFromYaml before full create resource {}", yamlName); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Starting to add inputs from yaml: {}", yamlName); final Resource genericResource = fetchAndSetDerivedFromGenericType(resource); resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative); log.trace("************* createResourceFromYaml after full create resource {}", yamlName); log.trace("************* Going to add inputs from yaml {}", yamlName); - if (resource.shouldGenerateInputs()) + if (resource.shouldGenerateInputs()) { generateAndAddInputsFromGenericTypeProperties(resource, genericResource); - + } final Map inputs = parsedToscaYamlInfo.getInputs(); resource = createInputsOnResource(resource, inputs); log.trace("************* Finish to add inputs from yaml {}", yamlName); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, - resource.getComponentMetadataForSupportLog(), - StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Finish to add inputs from yaml: {}", yamlName); if (resource.getResourceType() == ResourceTypeEnum.PNF) { log.trace("************* Adding generic properties to PNF"); - resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource, - genericResource.getProperties()); + resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource, genericResource.getProperties()); log.trace("************* Adding software information to PNF"); softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo); log.trace("************* Removing non-mano software information file from PNF"); - if (csarInfo.getSoftwareInformationPath().isPresent() && - !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) { - log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(), - "catalog-be", "Could not remove the software information file."); + if (csarInfo.getSoftwareInformationPath().isPresent() && !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) { + log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(), "catalog-be", + "Could not remove the software information file."); } } - - final Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo - .getInstances(); + final Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances(); log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations from yaml: {}",yamlName); - resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, - topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, - nodeName); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Start create nodes, RI and Relations from yaml: {}", yamlName); + resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml, + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName); log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, - resource.getComponentMetadataForSupportLog(), - StatusCode.COMPLETE,"Finished to create nodes, RI and Relation from yaml: {}",yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Finished to create nodes, RI and Relation from yaml: {}", yamlName); // validate update vf module group names final Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic - .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); + .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); if (validateUpdateVfGroupNamesRes.isRight()) { rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value()); @@ -1687,3781 +1440,3150 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { // add groups to resource final Map groups; log.trace("************* Going to add groups from yaml {}", yamlName); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(), - StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Start to add groups from yaml: {}", yamlName); if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { groups = validateUpdateVfGroupNamesRes.left().value(); } else { groups = parsedToscaYamlInfo.getGroups(); } - - final Either createGroupsOnResource = createGroupsOnResource(resource, groups); - if (createGroupsOnResource.isRight()) { - rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, - resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName); - throw new ByResponseFormatComponentException(createGroupsOnResource.right().value()); - } - resource = createGroupsOnResource.left().value(); - log.trace("************* Finished to add groups from yaml {}", yamlName); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, - resource.getComponentMetadataForSupportLog(), - StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName); - log.trace("************* Going to add artifacts from yaml {}", yamlName); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, - resource.getComponentMetadataForSupportLog(), - StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName); - - log.trace("************* Starting to add policies from yaml {}", yamlName); - Map policies = parsedToscaYamlInfo.getPolicies(); - if (MapUtils.isNotEmpty(policies)) { - resource = createPoliciesOnResource(resource, policies); - } - log.trace("************* Finished to add policies from yaml {}", yamlName); - - final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = - new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate); - - final Either createArtifactsEither = createOrUpdateArtifacts( - ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource, - nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); - if (createArtifactsEither.isRight()) { - rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, - resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}", - createArtifactsEither.right().value()); - throw new ByResponseFormatComponentException(createArtifactsEither.right().value()); - } - loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, - resource.getComponentMetadataForSupportLog(), - StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName()); - final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum); - ASDCKpiApi.countCreatedResourcesKPI(); - return resource; - + final Either createGroupsOnResource = createGroupsOnResource(resource, groups); + if (createGroupsOnResource.isRight()) { + rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR while adding groups from yaml: {}", yamlName); + throw new ByResponseFormatComponentException(createGroupsOnResource.right().value()); + } + resource = createGroupsOnResource.left().value(); + log.trace("************* Finished to add groups from yaml {}", yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Finished to add groups from yaml: {}", yamlName); + log.trace("************* Going to add artifacts from yaml {}", yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Started to add artifacts from yaml: {}", yamlName); + log.trace("************* Starting to add policies from yaml {}", yamlName); + Map policies = parsedToscaYamlInfo.getPolicies(); + if (MapUtils.isNotEmpty(policies)) { + resource = createPoliciesOnResource(resource, policies); + } + log.trace("************* Finished to add policies from yaml {}", yamlName); + final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, + nodeTypesArtifactsToCreate); + final Either createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, + yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + if (createArtifactsEither.isRight()) { + rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "error happened {}", createArtifactsEither.right().value()); + throw new ByResponseFormatComponentException(createArtifactsEither.right().value()); + } + loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Finished to add artifacts from yaml: " + resource.getToscaResourceName()); + final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum); + ASDCKpiApi.countCreatedResourcesKPI(); + return resource; } catch (final BusinessLogicException e) { - log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(), - "An error has occurred during resource and resource instance creation", e); + log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(), + "An error has occurred during resource and resource instance creation", e); rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ByResponseFormatComponentException(e.getResponseFormat()); } catch (final Exception e) { - log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(), - "An error has occurred during resource and resource instance creation", e); - rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); - throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); + log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(), + "An error has occurred during resource and resource instance creation", e); + rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } finally { if (!inTransaction) { janusGraphDao.commit(); - } - if (shouldLock) { - graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), - NodeTypeEnum.Resource); - } - } - } - - private void rollback(boolean inTransaction, Resource resource, List createdArtifacts, - List nodeTypesNewCreatedArtifacts) { - if (!inTransaction) { + } + if (shouldLock) { + graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); + } + } + } + + private void rollback(boolean inTransaction, Resource resource, List createdArtifacts, + List nodeTypesNewCreatedArtifacts) { + if (!inTransaction) { janusGraphDao.rollback(); - } - if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) { - createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); - log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), - resource.getName()); - } - } - - private Resource getResourceWithGroups(String resourceId) { - - ComponentParametersView filter = new ComponentParametersView(); - filter.setIgnoreGroups(false); - Either updatedResource = toscaOperationFacade.getToscaElement(resourceId, - filter); - if (updatedResource.isRight()) { - rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right() - .value()), resourceId); - } - return updatedResource.left() - .value(); - } - - private Either createGroupsOnResource(Resource resource, - Map groups) { - if (groups != null && !groups.isEmpty()) { - List groupsAsList = updateGroupsMembersUsingResource(groups, resource); - handleGroupsProperties(resource, groups); - fillGroupsFinalFields(groupsAsList); - Either, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, - groupsAsList, true); - if (createGroups.isRight()) { - return Either.right(createGroups.right() - .value()); - } - } - return Either.left(resource); - } - - private void handleGroupsProperties(Resource resource, Map groups) { - List inputs = resource.getInputs(); - if (MapUtils.isNotEmpty(groups)) { - groups.values() - .stream() - .filter(g -> isNotEmpty(g.getProperties())) - .flatMap(g -> g.getProperties() - .stream()) - .forEach(p -> handleGetInputs(p, inputs)); - } - } + } + if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) { + createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); + log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName()); + } + } - private Resource createPoliciesOnResource(Resource resource, Map policies) { - policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies); - return resource; - } - - private void handleGetInputs(PropertyDataDefinition property, List inputs) { - if (isNotEmpty(property.getGetInputValues())) { - if (inputs == null || inputs.isEmpty()) { - log.debug("Failed to add property {} to group. Inputs list is empty ", property); - rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() - .stream() - .map(GetInputValueDataDefinition::getInputName) - .collect(toList()) - .toString()); - } - ListIterator getInputValuesIter = property.getGetInputValues() - .listIterator(); - while (getInputValuesIter.hasNext()) { - GetInputValueDataDefinition getInput = getInputValuesIter.next(); - Either inputEither = findInputByName(inputs, getInput); - if (inputEither.isRight()) { - throw inputEither.right().value(); - } else { - InputDefinition input = inputEither.left().value(); - getInput.setInputId(input.getUniqueId()); - if (getInput.getGetInputIndex() != null) { - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - Either newInputEither = findInputByName(inputs, - getInputIndex); - if (newInputEither.isRight()) { - throw newInputEither.right().value(); - } else { - InputDefinition newInput = newInputEither.left().value(); - getInputIndex.setInputId(newInput.getUniqueId()); - } - getInputValuesIter.add(getInputIndex); - } - } - } - } - } - - static Either rollbackWithEither( - final JanusGraphDao janusGraphDao, - final ActionStatus actionStatus, - final String... params) { - if (janusGraphDao != null) - janusGraphDao.rollback(); - return Either.right(new ByActionStatusComponentException(actionStatus, params)); - } - - Either rollbackWithEither( - final ActionStatus actionStatus, - final String... params) { - return rollbackWithEither(janusGraphDao, actionStatus, params); - } - - private Either findInputByName(List inputs, GetInputValueDataDefinition getInput) { - - final String inputName = getInput != null ? getInput.getInputName() : ""; - - if(inputs == null || inputs.isEmpty()) { - log.debug("#findInputByName - Inputs list is empty"); - return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName); - } else { - Optional inputOpt = inputs.stream() - .filter(p -> p.getName().equals(inputName)) - .findFirst(); - if (!inputOpt.isPresent()) { - log.debug("#findInputByName - Failed to find the input {} ", inputName); - return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName); - } else { - return Either.left(inputOpt.get()); - } - } - } - - private void fillGroupsFinalFields(List groupsAsList) { - groupsAsList.forEach(groupDefinition -> { - groupDefinition.setInvariantName(groupDefinition.getName()); - groupDefinition.setCreatedFrom(CreatedFrom.CSAR); - }); - } - - private Resource updateGroupsOnResource(Resource resource, Map groups) { - if (isEmpty(groups)) { - return resource; - } - return updateOrCreateGroups(resource, groups); - } - - private Resource updateOrCreateGroups(Resource resource, Map groups) { - List groupsFromResource = resource.getGroups(); - List groupsAsList = updateGroupsMembersUsingResource(groups, resource); - List groupsToUpdate = new ArrayList<>(); - List groupsToDelete = new ArrayList<>(); - List groupsToCreate = new ArrayList<>(); - if (isNotEmpty(groupsFromResource)) { - addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate); - addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete); - } else { - groupsToCreate.addAll(groupsAsList); - } - if (isNotEmpty(groupsToCreate)) { - fillGroupsFinalFields(groupsToCreate); - if (isNotEmpty(groupsFromResource)) { - groupBusinessLogic.addGroups(resource, groupsToCreate, true) - .left() - .on(this::throwComponentException); - } else { - groupBusinessLogic.createGroups(resource, groupsToCreate, true) - .left() - .on(this::throwComponentException); - } - } - if (isNotEmpty(groupsToDelete)) { - groupBusinessLogic.deleteGroups(resource, groupsToDelete) - .left() - .on(this::throwComponentException); - } - if (isNotEmpty(groupsToUpdate)) { - groupBusinessLogic.updateGroups(resource, groupsToUpdate, true) - .left() - .on(this::throwComponentException); - } - return resource; - - } - - private void addGroupsToDelete(List groupsFromResource, List groupsAsList, - List groupsToDelete) { - for (GroupDefinition group : groupsFromResource) { - Optional op = groupsAsList.stream() - .filter(p -> p.getInvariantName() - .equalsIgnoreCase(group.getInvariantName())) - .findAny(); - if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts() - .isEmpty())) { - groupsToDelete.add(group); - } - } - } - - private void addGroupsToCreateOrUpdate(List groupsFromResource, List groupsAsList, - List groupsToUpdate, List groupsToCreate) { - for (GroupDefinition group : groupsAsList) { - Optional op = groupsFromResource.stream() - .filter(p -> p.getInvariantName() - .equalsIgnoreCase(group.getInvariantName())) - .findAny(); - if (op.isPresent()) { - GroupDefinition groupToUpdate = op.get(); - groupToUpdate.setMembers(group.getMembers()); - groupToUpdate.setCapabilities(group.getCapabilities()); - groupToUpdate.setProperties(group.getProperties()); - groupsToUpdate.add(groupToUpdate); - } else { - groupsToCreate.add(group); - } - } - } - - private Resource createInputsOnResource(Resource resource, Map inputs) { - List resourceProperties = resource.getInputs(); - if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) { - - Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, - resource); - if (createInputs.isRight()) { - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right() - .value()); - throw new ByResponseFormatComponentException(createInputs.right() - .value()); - } - resource.setInputs(createInputs.left().value()); - } - return resource; - } - - private List updateGroupsMembersUsingResource(Map groups, - Resource component) { - - List result = new ArrayList<>(); - List componentInstances = component.getComponentInstances(); - - if (groups != null) { - Either validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); - if (validateCyclicGroupsDependencies.isRight()) { - throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value()); - } - for (Entry entry : groups.entrySet()) { - String groupName = entry.getKey(); - GroupDefinition groupDefinition = entry.getValue(); - GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition); - updatedGroupDefinition.setMembers(null); - Map members = groupDefinition.getMembers(); - if (members != null) { - updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, - members); - } - result.add(updatedGroupDefinition); - } - } - return result; - } - - private void updateGroupMembers(Map groups, GroupDefinition updatedGroupDefinition, - Resource component, List componentInstances, String groupName, - Map members) { - Set compInstancesNames = members.keySet(); - - if (CollectionUtils.isEmpty(componentInstances)) { - String membersAstString = compInstancesNames.stream() - .collect(joining(",")); - log.debug( - "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", - membersAstString, groupName, component.getNormalizedName()); - throw new ByActionStatusComponentException( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, - groupName, component.getNormalizedName(), getComponentTypeForResponse(component)); - } - // Find all component instances with the member names - Map memberNames = componentInstances.stream() - .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); - memberNames.putAll(groups.keySet() - .stream() - .collect(toMap(g -> g, g -> ""))); - Map relevantInstances = memberNames.entrySet() - .stream() - .filter(n -> compInstancesNames.contains(n.getKey())) - .collect(toMap(Entry::getKey, Entry::getValue)); - - if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { - - List foundMembers = new ArrayList<>(); - if (relevantInstances != null) { - foundMembers = relevantInstances.keySet() - .stream() - .collect(toList()); - } - compInstancesNames.removeAll(foundMembers); - String membersAstString = compInstancesNames.stream() - .collect(joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, - component.getNormalizedName()); - throw new ByActionStatusComponentException( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, - groupName, component.getNormalizedName(), getComponentTypeForResponse(component)); - } - updatedGroupDefinition.setMembers(relevantInstances); - } - - /** - * 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 occurred 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(allGroups::containsKey) - . - // Add Filtered Elements to main Set - peek(allGroupMembers::add) - . - // Collect results - collect(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 = 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(allGroups::containsKey) - . - // Collect - collect(toSet()); - stop = allGroupMembers.containsAll(membersOfTypeGroup); - } - return stop; - } - - private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource, - Map uploadComponentInstanceInfoMap, String topologyTemplateYaml, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, - CsarInfo csarInfo, - Map>> nodeTypesArtifactsToCreate, - String nodeName) { - - log.debug("************* Going to create all nodes {}", yamlName); - handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName); - log.debug("************* Finished to create all nodes {}", yamlName); - log.debug("************* Going to create all resource instances {}", yamlName); - Map existingNodeTypesByResourceNames = new HashMap<>(); - resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap, - csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames); - log.debug("************* Finished to create all resource instances {}", yamlName); - log.debug("************* Going to create all relations {}", yamlName); - resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames); - log.debug("************* Finished to create all relations {}", yamlName); - log.debug("************* Going to create positions {}", yamlName); - compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier() - .getUserId()); - log.debug("************* Finished to set positions {}", yamlName); - return resource; - } - - private void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, - List artifactsToAdd) { - List vfcArtifactNames = vfcArtifacts.stream() - .map(ArtifactDataDefinition::getArtifactName) - .collect(toList()); - artifactsToAdd.stream() - .forEach(a -> { - if (!vfcArtifactNames.contains(a.getArtifactName())) { - vfcArtifacts.add(a); - } else { - log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName()); - } - }); - - } - - @SuppressWarnings("unchecked") - private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock, - Map>> nodeTypesArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, - CsarInfo csarInfo, String nodeName) { - try { - for (Entry nodeTypeEntry : nodeTypesInfo.entrySet()) { - if (nodeTypeEntry.getValue() - .isNested()) { - - handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, - csarInfo, nodeTypeEntry.getKey()); - log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); - } - } - Map mappedToscaTemplate = null; - if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) { - mappedToscaTemplate = nodeTypesInfo.get(nodeName) - .getMappedToscaTemplate(); - } - if (isEmpty(mappedToscaTemplate)) { - mappedToscaTemplate = (Map) new Yaml().load(topologyTemplateYaml); - } - createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, - nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); - } catch (ComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() - : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, - AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } catch (StorageException e) { - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, - AuditingActionEnum.IMPORT_RESOURCE); - throw e; - } - } - - 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.isUpdate()) { - 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, true, - 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, true, shouldLock, inTransaction); - - Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, - createdArtifacts, shouldLock, inTransaction, artifactOperation); - if (eitherCreateResult.isRight()) { - return Either.right(eitherCreateResult.right() - .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 (artifactOperation.isCreateOrLink()) { - createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar( - csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts); - } else { - Either result = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar( - csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, - inTransaction); - if ((result.left().value() instanceof Resource) && result.isLeft()) { - Resource service1 = (Resource) result.left().value(); - createArtifactsFromCsar = Either.left(service1); - } else { - createArtifactsFromCsar = Either.right(result.right().value()); - } - } - - 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.isUpdate() || operation.isDelete()) { - if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) { - Either handleDelete = artifactsBusinessLogic - .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), - resource, shouldLock, - inTransaction); - if (handleDelete.isRight()) { - result = Either.right(handleDelete.right() - .value()); - } else { - ArtifactDefinition value = handleDelete.left().value(); - String updatedArtifactId = value.getUniqueId(); - if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) { - resource.getDeploymentArtifacts().remove(updatedArtifactId); - } else { - resource.getArtifacts().remove(updatedArtifactId); - } - } - return result; - } - - if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) { - operation = 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()); - } - ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value(); - createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType); - } - - return result; - } - - private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) { - if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) { - resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact); - } else { - resource.getArtifacts().put(artifact.getArtifactLabel(), artifact); - } - } - - 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 (operation.isCreateOrLink() && 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 { - Either, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, - collectedWarningMessages); - if (artifactPathAndNameList.isRight()) { - return Either.right(getComponentsUtils().getResponseFormatByArtifactId( - ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right() - .value())); - } - EnumMap> vfCsarArtifactsToHandle = null; - - if (artifactOperation.isCreateOrLink()) { - vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left() - .value()); - } else { - Either>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle( - resource, artifactPathAndNameList.left() - .value(), - csarInfo.getModifier()); - - if (findVfCsarArtifactsToHandleRes.isRight()) { - resStatus = Either.right(findVfCsarArtifactsToHandleRes.right() - .value()); - } - if (resStatus == null) { - vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left() - .value(); - } - } - if (resStatus == null && vfCsarArtifactsToHandle != null) { - resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, - resStatus, vfCsarArtifactsToHandle); - } - if (resStatus == null) { - resStatus = Either.left(resource); - } - } catch (Exception e) { - resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e); - } finally { - CsarUtils.handleWarningMessages(collectedWarningMessages); - } - return resStatus; - } - - private Either processCsarArtifacts(CsarInfo csarInfo, Resource resource, - List createdArtifacts, boolean shouldLock, boolean inTransaction, - Either resStatus, - EnumMap> vfCsarArtifactsToHandle) { - 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(), - e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), - CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), - new ArtifactOperationInfo(false, false, - currArtifactOperationPair.getKey()), - createdArtifacts, e.isFromCsar(), shouldLock, inTransaction)) - // filter in only error - .filter(Either::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; - } - } - return resStatus; - } - - private Either, String> getValidArtifactNames(CsarInfo csarInfo, - Map>> collectedWarningMessages) { - 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(Either::isLeft) - // Convert from Either to NonMetaArtifactInfo - .map(e -> e.left() - .value()) - // collect to List - .collect(toList()); - 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(artifactPathAndNameList); - } - - 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(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(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.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE - || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { - result = false; - } - return result; - } - - private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource, - Map uploadResInstancesMap, Map existingNodeTypesByResourceNames) { - log.debug("#createResourceInstancesRelations - Going to create relations "); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start to create relations"); - List componentInstancesList = resource.getComponentInstances(); - if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) && - resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances { - log.debug( - "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", - resource.getUniqueId(), yamlName); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName); - BeEcompErrorManager.getInstance() - .logInternalDataError("createResourceInstancesRelations", - "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR); - throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - } - Map> instProperties = new HashMap<>(); - Map>> instCapabilities = new HashMap<>(); - Map>> instRequirements = new HashMap<>(); - Map> instDeploymentArtifacts = new HashMap<>(); - Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); - List relations = new ArrayList<>(); - Map> instInputs = new HashMap<>(); - - log.debug("#createResourceInstancesRelations - Before get all datatypes. "); - Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - JanusGraphOperationStatus status = allDataTypes.right() - .value(); - BeEcompErrorManager.getInstance() - .logInternalFlowError("UpdatePropertyValueOnComponentInstance", - "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName); - - } - Resource finalResource = resource; - uploadResInstancesMap.values() - .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, - instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, - instAttributes, existingNodeTypesByResourceNames, instInputs, i)); - resource.getComponentInstances() - .stream() - .filter(i -> !i.isCreatedFromCsar()) - .forEach(i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, - instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes)); - - associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties); - associateComponentInstanceInputsToComponent(yamlName, resource, instInputs); - associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); - associateArtifactsToInstances(yamlName, resource, instArtifacts); - associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); - associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); - addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations); - associateResourceInstances(yamlName, resource, relations); - handleSubstitutionMappings(resource, uploadResInstancesMap); - log.debug("************* in create relations, getResource start"); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"create relations"); - Either eitherGetResource = toscaOperationFacade - .getToscaFullElement(resource.getUniqueId()); - log.debug("************* in create relations, getResource end"); - if (eitherGetResource.isRight()) { - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR while create relations"); - throw new ByResponseFormatComponentException(componentsUtils - .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right() - .value()), resource)); - } - return eitherGetResource.left() - .value(); - } - - private void processUiComponentInstance(Resource oldResource, ComponentInstance instance, - Map>> instCapabilities, - Map>> instRequirements, - Map> instDeploymentArtifacts, - Map> instArtifacts, Map> instProperties, Map> instInputs, - Map> instAttributes) { - Optional foundInstance = findInstance(oldResource, instance); - if (foundInstance.isPresent()) { - if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) { - instCapabilities.put(instance, foundInstance.get().getCapabilities()); - } - if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) { - instRequirements.put(instance, foundInstance.get().getRequirements()); - } - if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) { - instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts()); - } - if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){ - instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts()); - } - if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) && - CollectionUtils - .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) { - instProperties.put(instance.getUniqueId(), - oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId())); - } - if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) && - CollectionUtils - .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) { - instInputs.put(instance.getUniqueId(), - oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId())); - } - if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) && - CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){ - instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new).collect(toList())); - } - } - } - - private Optional findInstance(Resource oldResource, ComponentInstance instance) { - if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) { - return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst(); - } - return Optional.empty(); - } - - private void associateResourceInstances(String yamlName, Resource resource, - List relations) { - Either, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations); - - if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) { - StorageOperationStatus status = relationsEither.right().value(); - log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), - status); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName); - } else { - setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value()); - } - } - - private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, - Map> instAttributes) { - StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, - resource); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), - yamlName); - } - } - - private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, - Map>> instCapabilities, - Map>> instRequirements) { - StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, - resource); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - } - } - - private void associateArtifactsToInstances(String yamlName, Resource resource, - Map> instArtifacts) { - StorageOperationStatus addArtToInst; - - addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - } - } - - private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, - Map> instDeploymentArtifacts) { - StorageOperationStatus addArtToInst = toscaOperationFacade - .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - } - } - - private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, - Map> instInputs) { - if (MapUtils.isNotEmpty(instInputs)) { - Either>, StorageOperationStatus> addInputToInst = toscaOperationFacade - .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); - if (addInputToInst.isRight()) { - - StorageOperationStatus addInputToInstError = addInputToInst.right().value(); - log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), - addInputToInstError); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName); - } - setComponentInstanceInputsOnComponent(resource, instInputs); - } - } - - private void setComponentInstanceInputsOnComponent(Resource resource, Map> instInputs) { - Map> componentInstancesInputs = resource.getComponentInstancesInputs(); - if (componentInstancesInputs == null) - componentInstancesInputs = new HashMap<>(); - componentInstancesInputs.putAll(instInputs); - resource.setComponentInstancesInputs(componentInstancesInputs); - } - - private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, - Map> instProperties) { - Either>, StorageOperationStatus> addPropToInst = toscaOperationFacade - .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); - if (addPropToInst.isRight()) { - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR while associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value()); - StorageOperationStatus storageOperationStatus = addPropToInst.right().value(); - log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), - storageOperationStatus); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName); - } - setComponentInstancePropertiesOnComponent(resource, instProperties); - } - - private void setComponentInstancePropertiesOnComponent(Resource resource, Map> instProperties) { - Map> componentInstanceProps = resource.getComponentInstancesProperties(); - if (componentInstanceProps == null ) - componentInstanceProps = new HashMap<>(); - componentInstanceProps.putAll(instProperties); - resource.setComponentInstancesProperties(componentInstanceProps); - } - - private void handleSubstitutionMappings(Resource resource, - Map uploadResInstancesMap) { - if (resource.getResourceType() == ResourceTypeEnum.CVFC) { - Either getResourceRes = - updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap); - if (getResourceRes.isRight()) { - ResponseFormat responseFormat = componentsUtils - .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right() - .value()), resource); - throw new ByResponseFormatComponentException(responseFormat); - } - } - } - - private void addRelationsToRI(String yamlName, Resource resource, - Map uploadResInstancesMap, - List componentInstancesList, List relations) { - 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); - throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - } - - ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); - if (addRelationToRiRes.getStatus() != 200) { - throw new ByResponseFormatComponentException(addRelationToRiRes); - } - } - - } - - private void setResourceInstanceRelationsOnComponent(Resource resource, List relations) { - if (resource.getComponentInstancesRelations() != null) { - resource.getComponentInstancesRelations().addAll(relations); - } else { - resource.setComponentInstancesRelations(relations); - } - } - - private void processComponentInstance(String yamlName, Resource resource, - List componentInstancesList, - Either, JanusGraphOperationStatus> allDataTypes, - Map> instProperties, - Map>> instCapabilties, - Map>> instRequirements, - Map> instDeploymentArtifacts, - Map> instArtifacts, - Map> instAttributes, - Map originCompMap, - Map> instInputs, - UploadComponentInstanceInfo uploadComponentInstanceInfo) { - Optional currentCompInstanceOpt = componentInstancesList.stream() - .filter(i -> i.getName() - .equals(uploadComponentInstanceInfo.getName())) - .findFirst(); - if (!currentCompInstanceOpt.isPresent()) { - 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); - throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - } - ComponentInstance currentCompInstance = currentCompInstanceOpt.get(); - String resourceInstanceId = currentCompInstance.getUniqueId(); - Resource originResource = getOriginResource(originCompMap, currentCompInstance); - if (isNotEmpty(originResource.getRequirements())) { - instRequirements.put(currentCompInstance, originResource.getRequirements()); - } - if (isNotEmpty(originResource.getCapabilities())) { - processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, - currentCompInstance, originResource); - } - 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, instProperties, allDataTypes.left() - .value()); - if (addPropertiesValueToRiRes.getStatus() != 200) { - throw new ByResponseFormatComponentException(addPropertiesValueToRiRes); - } - } else { - addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs, - allDataTypes.left() - .value()); - } - } - - private Resource getOriginResource(Map originCompMap, ComponentInstance currentCompInstance) { - 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); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right() - .value()), currentCompInstance.getComponentUid()); - } - originResource = getOriginResourceRes.left() - .value(); - originCompMap.put(originResource.getUniqueId(), originResource); - } else { - originResource = originCompMap.get(currentCompInstance.getComponentUid()); - } - return originResource; - } - - private void processComponentInstanceCapabilities( - Either, JanusGraphOperationStatus> allDataTypes, - Map>> instCapabilties, - UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, - Resource originResource) { - Map> originCapabilities; - if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { - originCapabilities = new HashMap<>(); - Map> newPropertiesMap = new HashMap<>(); - originResource.getCapabilities() - .forEach((k, v) -> addCapabilities(originCapabilities, k, v)); - uploadComponentInstanceInfo.getCapabilities() - .values() - .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l)); - updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap); - } else { - originCapabilities = originResource.getCapabilities(); - } - instCapabilties.put(currentCompInstance, originCapabilities); - } - - private void updateCapabilityPropertiesValues( - Either, JanusGraphOperationStatus> allDataTypes, - Map> originCapabilities, - Map> newPropertiesMap) { - originCapabilities.values() - .stream() - .flatMap(Collection::stream) - .filter(c -> newPropertiesMap.containsKey(c.getName())) - .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), - allDataTypes.left() - .value())); - } - - private void addCapabilitiesProperties(Map> newPropertiesMap, - List capabilities) { - for (UploadCapInfo capability : capabilities) { - if (isNotEmpty(capability.getProperties())) { - newPropertiesMap.put(capability.getName(), capability.getProperties() - .stream() - .collect(toMap(UploadInfo::getName, p -> p))); - } - } - } - - private void addCapabilities(Map> originCapabilities, String type, - List capabilities) { - List list = capabilities.stream() - .map(CapabilityDefinition::new) - .collect(toList()); - originCapabilities.put(type, list); - } - - private void updatePropertyValues(List properties, - Map newProperties, Map allDataTypes) { - properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes)); - } - - private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo, - Map allDataTypes) { - String value = null; - List getInputs = null; - boolean isValidate = true; - if (null != propertyInfo && propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); - } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - } - property.setValue(value); - return validatePropValueBeforeCreate(property, value, isValidate, 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.associateOrAddCalculatedCapReq(updatedInstCapabilities, - updatedInstRequirements, resource); - 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 (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(toList())); - } - } - if (isNotEmpty(updatedRequirements)) { - updatedInstRequirements.put(instance, updatedRequirements); - } - } - - private void fillUpdatedInstCapabilities( - Map>> updatedInstCapabilties, - ComponentInstance instance, Map capabilitiesNamesToUpdate) { - Map> updatedCapabilities = new HashMap<>(); - Set updatedCapNames = new HashSet<>(); - if (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(toList())); - } - } - if (isNotEmpty(updatedCapabilities)) { - updatedInstCapabilties.put(instance, updatedCapabilities); - } - } - - private ResponseFormat addRelationToRI(String yamlName, Resource resource, - UploadComponentInstanceInfo nodesInfoValue, List relations) { - List componentInstancesList = resource.getComponentInstances(); - - ComponentInstance currentCompInstance = null; - - for (ComponentInstance compInstance : componentInstancesList) { - - if (compInstance.getName() - .equals(nodesInfoValue.getName())) { - currentCompInstance = compInstance; - break; - } - - } - - if (currentCompInstance == null) { - log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId()); - BeEcompErrorManager.getInstance() - .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, - resource.getUniqueId(), ErrorSeverity.ERROR); - return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - } - String resourceInstanceId = currentCompInstance.getUniqueId(); - - Map> regMap = nodesInfoValue.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()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Started to create relations on instance: {}",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, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName()); - if (eitherReqStatus.isRight()) { - log.debug("failed to find available requirement {} status is {}", regName, - eitherReqStatus.right() - .value()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while search 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()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR 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); - return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - } - 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()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR available 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); - return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - } - 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) { - return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, - Resource originResource, ComponentInstance currentCompInstance, - Map> instInputs, Map allDataTypes) { - Map> propMap = uploadComponentInstanceInfo.getProperties(); - if (MapUtils.isNotEmpty(propMap)) { - Map currPropertiesMap = new HashMap<>(); - List instPropList = new ArrayList<>(); - - if (CollectionUtils.isEmpty(originResource.getInputs())) { - log.debug("failed to find properties "); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties"); - throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND); - } - originResource.getInputs() - .forEach(p -> addInput(currPropertiesMap, p)); - for (List propertyList : propMap.values()) { - processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, - propertyList); - } - currPropertiesMap.values() - .forEach(p -> instPropList.add(new ComponentInstanceInput(p))); - instInputs.put(currentCompInstance.getUniqueId(), instPropList); - } - } - - private void processProperty(Resource resource, ComponentInstance currentCompInstance, - Map allDataTypes, Map currPropertiesMap, - List instPropList, List propertyList) { - UploadPropInfo propertyInfo = propertyList.get(0); - String propName = propertyInfo.getName(); - if (!currPropertiesMap.containsKey(propName)) { - loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR failed to find property: {}",propName); - log.debug("failed to find property {} ", propName); - throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName); - } - 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 = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); - } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - } - property = new ComponentInstanceInput(curPropertyDef, value, null); + private Resource getResourceWithGroups(String resourceId) { + ComponentParametersView filter = new ComponentParametersView(); + filter.setIgnoreGroups(false); + Either updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter); + if (updatedResource.isRight()) { + rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId); + } + return updatedResource.left().value(); + } - String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); + private Either createGroupsOnResource(Resource resource, Map groups) { + if (groups != null && !groups.isEmpty()) { + List groupsAsList = updateGroupsMembersUsingResource(groups, resource); + handleGroupsProperties(resource, groups); + fillGroupsFinalFields(groupsAsList); + Either, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, groupsAsList, true); + if (createGroups.isRight()) { + return Either.right(createGroups.right().value()); + } + } + return Either.left(resource); + } + + private void handleGroupsProperties(Resource resource, Map groups) { + List inputs = resource.getInputs(); + if (MapUtils.isNotEmpty(groups)) { + groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream()) + .forEach(p -> handleGetInputs(p, inputs)); + } + } + + private Resource createPoliciesOnResource(Resource resource, Map policies) { + policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies); + return resource; + } + + private void handleGetInputs(PropertyDataDefinition property, List inputs) { + if (isNotEmpty(property.getGetInputValues())) { + if (inputs == null || inputs.isEmpty()) { + log.debug("Failed to add property {} to group. Inputs list is empty ", property); + rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, + property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString()); + } + ListIterator getInputValuesIter = property.getGetInputValues().listIterator(); + while (getInputValuesIter.hasNext()) { + GetInputValueDataDefinition getInput = getInputValuesIter.next(); + Either inputEither = findInputByName(inputs, getInput); + if (inputEither.isRight()) { + throw inputEither.right().value(); + } else { + InputDefinition input = inputEither.left().value(); + getInput.setInputId(input.getUniqueId()); + if (getInput.getGetInputIndex() != null) { + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + Either newInputEither = findInputByName(inputs, getInputIndex); + if (newInputEither.isRight()) { + throw newInputEither.right().value(); + } else { + InputDefinition newInput = newInputEither.left().value(); + getInputIndex.setInputId(newInput.getUniqueId()); + } + getInputValuesIter.add(getInputIndex); + } + } + } + } + } + + Either rollbackWithEither(final ActionStatus actionStatus, final String... params) { + return rollbackWithEither(janusGraphDao, actionStatus, params); + } + + private Either findInputByName(List inputs, GetInputValueDataDefinition getInput) { + final String inputName = getInput != null ? getInput.getInputName() : ""; + if (inputs == null || inputs.isEmpty()) { + log.debug("#findInputByName - Inputs list is empty"); + return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName); + } else { + Optional inputOpt = inputs.stream().filter(p -> p.getName().equals(inputName)).findFirst(); + if (!inputOpt.isPresent()) { + log.debug("#findInputByName - Failed to find the input {} ", inputName); + return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName); + } else { + return Either.left(inputOpt.get()); + } + } + } + + private void fillGroupsFinalFields(List groupsAsList) { + groupsAsList.forEach(groupDefinition -> { + groupDefinition.setInvariantName(groupDefinition.getName()); + groupDefinition.setCreatedFrom(CreatedFrom.CSAR); + }); + } + + private Resource updateGroupsOnResource(Resource resource, Map groups) { + if (isEmpty(groups)) { + return resource; + } + return updateOrCreateGroups(resource, groups); + } + + private Resource updateOrCreateGroups(Resource resource, Map groups) { + List groupsFromResource = resource.getGroups(); + List groupsAsList = updateGroupsMembersUsingResource(groups, resource); + List groupsToUpdate = new ArrayList<>(); + List groupsToDelete = new ArrayList<>(); + List groupsToCreate = new ArrayList<>(); + if (isNotEmpty(groupsFromResource)) { + addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate); + addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete); + } else { + groupsToCreate.addAll(groupsAsList); + } + if (isNotEmpty(groupsToCreate)) { + fillGroupsFinalFields(groupsToCreate); + if (isNotEmpty(groupsFromResource)) { + groupBusinessLogic.addGroups(resource, groupsToCreate, true).left().on(this::throwComponentException); + } else { + groupBusinessLogic.createGroups(resource, groupsToCreate, true).left().on(this::throwComponentException); + } + } + if (isNotEmpty(groupsToDelete)) { + groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(this::throwComponentException); + } + if (isNotEmpty(groupsToUpdate)) { + groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left().on(this::throwComponentException); + } + return resource; + } + + private void addGroupsToDelete(List groupsFromResource, List groupsAsList, + List groupsToDelete) { + for (GroupDefinition group : groupsFromResource) { + Optional op = groupsAsList.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())) + .findAny(); + if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) { + groupsToDelete.add(group); + } + } + } + + private void addGroupsToCreateOrUpdate(List groupsFromResource, List groupsAsList, + List groupsToUpdate, List groupsToCreate) { + for (GroupDefinition group : groupsAsList) { + Optional op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())) + .findAny(); + if (op.isPresent()) { + GroupDefinition groupToUpdate = op.get(); + groupToUpdate.setMembers(group.getMembers()); + groupToUpdate.setCapabilities(group.getCapabilities()); + groupToUpdate.setProperties(group.getProperties()); + groupsToUpdate.add(groupToUpdate); + } else { + groupsToCreate.add(group); + } + } + } + + private Resource createInputsOnResource(Resource resource, Map inputs) { + List resourceProperties = resource.getInputs(); + if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) { + Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource); + if (createInputs.isRight()) { + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "failed to add inputs from yaml: {}", createInputs.right().value()); + throw new ByResponseFormatComponentException(createInputs.right().value()); + } + resource.setInputs(createInputs.left().value()); + } + return resource; + } + + private List updateGroupsMembersUsingResource(Map groups, Resource component) { + List result = new ArrayList<>(); + List componentInstances = component.getComponentInstances(); + if (groups != null) { + Either validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); + if (validateCyclicGroupsDependencies.isRight()) { + throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value()); + } + for (Entry entry : groups.entrySet()) { + String groupName = entry.getKey(); + GroupDefinition groupDefinition = entry.getValue(); + GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition); + updatedGroupDefinition.setMembers(null); + Map members = groupDefinition.getMembers(); + if (members != null) { + updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members); + } + result.add(updatedGroupDefinition); + } + } + return result; + } + + private void updateGroupMembers(Map groups, GroupDefinition updatedGroupDefinition, Resource component, + List componentInstances, String groupName, Map members) { + Set compInstancesNames = members.keySet(); + if (CollectionUtils.isEmpty(componentInstances)) { + String membersAstString = compInstancesNames.stream().collect(joining(",")); + log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, + groupName, component.getNormalizedName()); + throw new ByActionStatusComponentException(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, + component.getNormalizedName(), getComponentTypeForResponse(component)); + } + // Find all component instances with the member names + Map memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> ""))); + Map relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())) + .collect(toMap(Entry::getKey, Entry::getValue)); + if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { + List foundMembers = new ArrayList<>(); + if (relevantInstances != null) { + foundMembers = relevantInstances.keySet().stream().collect(toList()); + } + compInstancesNames.removeAll(foundMembers); + String membersAstString = compInstancesNames.stream().collect(joining(",")); + log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName()); + throw new ByActionStatusComponentException(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, + component.getNormalizedName(), getComponentTypeForResponse(component)); + } + updatedGroupDefinition.setMembers(relevantInstances); + } + + /** + * 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 occurred 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(allGroups::containsKey). + // Add Filtered Elements to main Set + peek(allGroupMembers::add). + // Collect results + collect(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 = 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(allGroups::containsKey). + // Collect + collect(toSet()); + stop = allGroupMembers.containsAll(membersOfTypeGroup); + } + return stop; + } + + private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource, + Map uploadComponentInstanceInfoMap, + String topologyTemplateYaml, List nodeTypesNewCreatedArtifacts, + Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + String nodeName) { + log.debug("************* Going to create all nodes {}", yamlName); + handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, + csarInfo, nodeName); + log.debug("************* Finished to create all nodes {}", yamlName); + log.debug("************* Going to create all resource instances {}", yamlName); + Map existingNodeTypesByResourceNames = new HashMap<>(); + resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes(), + existingNodeTypesByResourceNames); + log.debug("************* Finished to create all resource instances {}", yamlName); + log.debug("************* Going to create all relations {}", yamlName); + resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, + existingNodeTypesByResourceNames); + log.debug("************* Finished to create all relations {}", yamlName); + log.debug("************* Going to create positions {}", yamlName); + compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId()); + log.debug("************* Finished to set positions {}", yamlName); + return resource; + } + + private void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, List artifactsToAdd) { + List vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList()); + artifactsToAdd.stream().forEach(a -> { + if (!vfcArtifactNames.contains(a.getArtifactName())) { + vfcArtifacts.add(a); + } else { + log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName()); + } + }); + } + + @SuppressWarnings("unchecked") + private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, CsarInfo csarInfo, + String nodeName) { + try { + for (Entry nodeTypeEntry : nodeTypesInfo.entrySet()) { + if (nodeTypeEntry.getValue().isNested()) { + handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypeEntry.getKey()); + log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); + } + } + Map mappedToscaTemplate = null; + if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) { + mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); + } + if (isEmpty(mappedToscaTemplate)) { + mappedToscaTemplate = (Map) new Yaml().load(topologyTemplateYaml); + } + createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); + } catch (ComponentException e) { + ResponseFormat responseFormat = + e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + throw e; + } catch (StorageException e) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + throw e; + } + } + + 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.isUpdate()) { + 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, true, 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, true, shouldLock, + inTransaction); + Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock, + inTransaction, artifactOperation); + if (eitherCreateResult.isRight()) { + return Either.right(eitherCreateResult.right().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 (artifactOperation.isCreateOrLink()) { + createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic + .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts); + } else { + Either result = csarArtifactsAndGroupsBusinessLogic + .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, + inTransaction); + if ((result.left().value() instanceof Resource) && result.isLeft()) { + Resource service1 = (Resource) result.left().value(); + createArtifactsFromCsar = Either.left(service1); + } else { + createArtifactsFromCsar = Either.right(result.right().value()); + } + } + 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.isUpdate() || operation.isDelete()) { + if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) { + Either handleDelete = artifactsBusinessLogic + .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), resource, shouldLock, inTransaction); + if (handleDelete.isRight()) { + result = Either.right(handleDelete.right().value()); + } else { + ArtifactDefinition value = handleDelete.left().value(); + String updatedArtifactId = value.getUniqueId(); + if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) { + resource.getDeploymentArtifacts().remove(updatedArtifactId); + } else { + resource.getArtifacts().remove(updatedArtifactId); + } + } + return result; + } + if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) { + operation = 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()); + } + ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value(); + createOrUpdateResourceWithUpdatedArtifact(artifactDefinition, resource, artifactGroupType); + } + return result; + } + + private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) { + if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) { + resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact); + } else { + resource.getArtifacts().put(artifact.getArtifactLabel(), artifact); + } + } + + 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 (operation.isCreateOrLink() && 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 { + Either, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages); + if (artifactPathAndNameList.isRight()) { + return Either.right( + getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value())); + } + EnumMap> vfCsarArtifactsToHandle = null; + if (artifactOperation.isCreateOrLink()) { + vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value()); + } else { + Either>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle( + resource, artifactPathAndNameList.left().value(), csarInfo.getModifier()); + if (findVfCsarArtifactsToHandleRes.isRight()) { + resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value()); + } + if (resStatus == null) { + vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value(); + } + } + if (resStatus == null && vfCsarArtifactsToHandle != null) { + resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle); + } + if (resStatus == null) { + resStatus = Either.left(resource); + } + } catch (Exception e) { + resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e); + } finally { + CsarUtils.handleWarningMessages(collectedWarningMessages); + } + return resStatus; + } + + private Either processCsarArtifacts(CsarInfo csarInfo, Resource resource, List createdArtifacts, + boolean shouldLock, boolean inTransaction, + Either resStatus, + EnumMap> vfCsarArtifactsToHandle) { + 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(), + e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR, + e.getArtifactUniqueId(), new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, + e.isFromCsar(), shouldLock, inTransaction)) + // filter in only error + .filter(Either::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; + } + } + return resStatus; + } + + private Either, String> getValidArtifactNames(CsarInfo csarInfo, + Map>> collectedWarningMessages) { + 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(Either::isLeft) + // Convert from Either to NonMetaArtifactInfo + .map(e -> e.left().value()) + // collect to List + .collect(toList()); + 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(artifactPathAndNameList); + } + + 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(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(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.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE + || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { + result = false; + } + return result; + } + + private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource, + Map uploadResInstancesMap, + Map existingNodeTypesByResourceNames) { + log.debug("#createResourceInstancesRelations - Going to create relations "); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Start to create relations"); + List componentInstancesList = resource.getComponentInstances(); + if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) && + resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances { + log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", + resource.getUniqueId(), yamlName); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "No instances found in the resource: {}, is empty, yaml template file name: {}", resource.getName(), yamlName); + BeEcompErrorManager.getInstance() + .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", + ErrorSeverity.ERROR); + throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + Map> instProperties = new HashMap<>(); + Map>> instCapabilities = new HashMap<>(); + Map>> instRequirements = new HashMap<>(); + Map> instDeploymentArtifacts = new HashMap<>(); + Map> instArtifacts = new HashMap<>(); + Map> instAttributes = new HashMap<>(); + List relations = new ArrayList<>(); + Map> instInputs = new HashMap<>(); + log.debug("#createResourceInstancesRelations - Before get all datatypes. "); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + JanusGraphOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance() + .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, + ErrorSeverity.ERROR); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR while update property value on instance. Status is: " + status); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName); + } + Resource finalResource = resource; + uploadResInstancesMap.values().forEach( + i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities, + instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, existingNodeTypesByResourceNames, instInputs, i)); + resource.getComponentInstances().stream().filter(i -> !i.isCreatedFromCsar()).forEach( + i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, + instProperties, instInputs, instAttributes)); + associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties); + associateComponentInstanceInputsToComponent(yamlName, resource, instInputs); + associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); + associateArtifactsToInstances(yamlName, resource, instArtifacts); + associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); + associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); + addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations); + associateResourceInstances(yamlName, resource, relations); + handleSubstitutionMappings(resource, uploadResInstancesMap); + log.debug("************* in create relations, getResource start"); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, "create relations"); + Either eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId()); + log.debug("************* in create relations, getResource end"); + if (eitherGetResource.isRight()) { + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR while create relations"); + throw new ByResponseFormatComponentException( + componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource)); + } + return eitherGetResource.left().value(); + } + + private void processUiComponentInstance(Resource oldResource, ComponentInstance instance, + Map>> instCapabilities, + Map>> instRequirements, + Map> instDeploymentArtifacts, + Map> instArtifacts, + Map> instProperties, + Map> instInputs, + Map> instAttributes) { + Optional foundInstance = findInstance(oldResource, instance); + if (foundInstance.isPresent()) { + if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) { + instCapabilities.put(instance, foundInstance.get().getCapabilities()); + } + if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) { + instRequirements.put(instance, foundInstance.get().getRequirements()); + } + if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) { + instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts()); + } + if (MapUtils.isNotEmpty(foundInstance.get().getArtifacts())) { + instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts()); + } + if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) && CollectionUtils + .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) { + instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId())); + } + if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) && CollectionUtils + .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) { + instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId())); + } + if (MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) && CollectionUtils + .isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))) { + instAttributes.put(instance.getUniqueId(), + oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new) + .collect(toList())); + } + } + } + + private Optional findInstance(Resource oldResource, ComponentInstance instance) { + if (oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) { + return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst(); + } + return Optional.empty(); + } + + private void associateResourceInstances(String yamlName, Resource resource, List relations) { + Either, StorageOperationStatus> relationsEither = toscaOperationFacade + .associateResourceInstances(resource, resource.getUniqueId(), relations); + if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) { + StorageOperationStatus status = relationsEither.right().value(); + log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName); + } else { + setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value()); + } + } + + private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, + Map> instAttributes) { + StorageOperationStatus addArtToInst; + addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + } + } + + private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, + Map>> instCapabilities, + Map>> instRequirements) { + StorageOperationStatus addArtToInst; + addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + } + } + + private void associateArtifactsToInstances(String yamlName, Resource resource, Map> instArtifacts) { + StorageOperationStatus addArtToInst; + addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + } + } + + private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, + Map> instDeploymentArtifacts) { + StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + } + } + + private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, + Map> instInputs) { + if (MapUtils.isNotEmpty(instInputs)) { + Either>, StorageOperationStatus> addInputToInst = toscaOperationFacade + .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); + if (addInputToInst.isRight()) { + StorageOperationStatus addInputToInstError = addInputToInst.right().value(); + log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInstError); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName); + } + setComponentInstanceInputsOnComponent(resource, instInputs); + } + } + + private void setComponentInstanceInputsOnComponent(Resource resource, Map> instInputs) { + Map> componentInstancesInputs = resource.getComponentInstancesInputs(); + if (componentInstancesInputs == null) { + componentInstancesInputs = new HashMap<>(); + } + componentInstancesInputs.putAll(instInputs); + resource.setComponentInstancesInputs(componentInstancesInputs); + } + + private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, + Map> instProperties) { + Either>, StorageOperationStatus> addPropToInst = toscaOperationFacade + .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); + if (addPropToInst.isRight()) { + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR while associate compnent insatnce properties of resource: {} status is: {}", resource.getName(), + addPropToInst.right().value()); + StorageOperationStatus storageOperationStatus = addPropToInst.right().value(); + log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), storageOperationStatus); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName); + } + setComponentInstancePropertiesOnComponent(resource, instProperties); + } + + private void setComponentInstancePropertiesOnComponent(Resource resource, Map> instProperties) { + Map> componentInstanceProps = resource.getComponentInstancesProperties(); + if (componentInstanceProps == null) { + componentInstanceProps = new HashMap<>(); + } + componentInstanceProps.putAll(instProperties); + resource.setComponentInstancesProperties(componentInstanceProps); + } + + private void handleSubstitutionMappings(Resource resource, Map uploadResInstancesMap) { + if (resource.getResourceType() == ResourceTypeEnum.CVFC) { + Either getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap); + if (getResourceRes.isRight()) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); + throw new ByResponseFormatComponentException(responseFormat); + } + } + } + + private void addRelationsToRI(String yamlName, Resource resource, Map uploadResInstancesMap, + List componentInstancesList, List relations) { + 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); + throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); + if (addRelationToRiRes.getStatus() != 200) { + throw new ByResponseFormatComponentException(addRelationToRiRes); + } + } + } + + private void setResourceInstanceRelationsOnComponent(Resource resource, List relations) { + if (resource.getComponentInstancesRelations() != null) { + resource.getComponentInstancesRelations().addAll(relations); + } else { + resource.setComponentInstancesRelations(relations); + } + } + + private void processComponentInstance(String yamlName, Resource resource, List componentInstancesList, + Either, JanusGraphOperationStatus> allDataTypes, + Map> instProperties, + Map>> instCapabilties, + Map>> instRequirements, + Map> instDeploymentArtifacts, + Map> instArtifacts, + Map> instAttributes, Map originCompMap, + Map> instInputs, + UploadComponentInstanceInfo uploadComponentInstanceInfo) { + Optional currentCompInstanceOpt = componentInstancesList.stream() + .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst(); + if (!currentCompInstanceOpt.isPresent()) { + 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); + throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + ComponentInstance currentCompInstance = currentCompInstanceOpt.get(); + String resourceInstanceId = currentCompInstance.getUniqueId(); + Resource originResource = getOriginResource(originCompMap, currentCompInstance); + if (isNotEmpty(originResource.getRequirements())) { + instRequirements.put(currentCompInstance, originResource.getRequirements()); + } + if (isNotEmpty(originResource.getCapabilities())) { + processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource); + } + 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, instProperties, allDataTypes.left().value()); + if (addPropertiesValueToRiRes.getStatus() != 200) { + throw new ByResponseFormatComponentException(addPropertiesValueToRiRes); + } + } else { + addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs, allDataTypes.left().value()); + } + } + + private Resource getOriginResource(Map originCompMap, ComponentInstance currentCompInstance) { + 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); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), + currentCompInstance.getComponentUid()); + } + originResource = getOriginResourceRes.left().value(); + originCompMap.put(originResource.getUniqueId(), originResource); + } else { + originResource = originCompMap.get(currentCompInstance.getComponentUid()); + } + return originResource; + } + + private void processComponentInstanceCapabilities(Either, JanusGraphOperationStatus> allDataTypes, + Map>> instCapabilties, + UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, + Resource originResource) { + Map> originCapabilities; + if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { + originCapabilities = new HashMap<>(); + Map> newPropertiesMap = new HashMap<>(); + originResource.getCapabilities().forEach((k, v) -> addCapabilities(originCapabilities, k, v)); + uploadComponentInstanceInfo.getCapabilities().values().forEach(l -> addCapabilitiesProperties(newPropertiesMap, l)); + updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap); + } else { + originCapabilities = originResource.getCapabilities(); + } + instCapabilties.put(currentCompInstance, originCapabilities); + } + + private void updateCapabilityPropertiesValues(Either, JanusGraphOperationStatus> allDataTypes, + Map> originCapabilities, + Map> newPropertiesMap) { + originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName())) + .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value())); + } + + private void addCapabilitiesProperties(Map> newPropertiesMap, List capabilities) { + for (UploadCapInfo capability : capabilities) { + if (isNotEmpty(capability.getProperties())) { + newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p))); + } + } + } + + private void addCapabilities(Map> originCapabilities, String type, List capabilities) { + List list = capabilities.stream().map(CapabilityDefinition::new).collect(toList()); + originCapabilities.put(type, list); + } + + private void updatePropertyValues(List properties, Map newProperties, + Map allDataTypes) { + properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes)); + } + + private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo, + Map allDataTypes) { + String value = null; + List getInputs = null; + boolean isValidate = true; + if (null != propertyInfo && propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); + } else { + value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + } + property.setValue(value); + return validatePropValueBeforeCreate(property, value, isValidate, 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.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource); + 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 (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(toList())); + } + } + if (isNotEmpty(updatedRequirements)) { + updatedInstRequirements.put(instance, updatedRequirements); + } + } + + private void fillUpdatedInstCapabilities(Map>> updatedInstCapabilties, + ComponentInstance instance, Map capabilitiesNamesToUpdate) { + Map> updatedCapabilities = new HashMap<>(); + Set updatedCapNames = new HashSet<>(); + if (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(toList())); + } + } + if (isNotEmpty(updatedCapabilities)) { + updatedInstCapabilties.put(instance, updatedCapabilities); + } + } + + private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, + List relations) { + List componentInstancesList = resource.getComponentInstances(); + ComponentInstance currentCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + if (compInstance.getName().equals(nodesInfoValue.getName())) { + currentCompInstance = compInstance; + break; + } + } + if (currentCompInstance == null) { + log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(), + ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + String resourceInstanceId = currentCompInstance.getUniqueId(); + Map> regMap = nodesInfoValue.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()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "Started to create relations on instance: {}", 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, nodesInfoValue, + currentCompInstance, uploadRegInfo.getCapabilityName()); + if (eitherReqStatus.isRight()) { + log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR while search 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()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR 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); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + 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()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR available 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); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + } + 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) { + return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, + ComponentInstance currentCompInstance, Map> instInputs, + Map allDataTypes) { + Map> propMap = uploadComponentInstanceInfo.getProperties(); + if (MapUtils.isNotEmpty(propMap)) { + Map currPropertiesMap = new HashMap<>(); + List instPropList = new ArrayList<>(); + if (CollectionUtils.isEmpty(originResource.getInputs())) { + log.debug("failed to find properties "); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR while try to find properties"); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND); + } + originResource.getInputs().forEach(p -> addInput(currPropertiesMap, p)); + for (List propertyList : propMap.values()) { + processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList); + } + currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p))); + instInputs.put(currentCompInstance.getUniqueId(), instPropList); + } + } + + private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map allDataTypes, + Map currPropertiesMap, List instPropList, + List propertyList) { + UploadPropInfo propertyInfo = propertyList.get(0); + String propName = propertyInfo.getName(); + if (!currPropertiesMap.containsKey(propName)) { + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR failed to find property: {}", propName); + log.debug("failed to find property {} ", propName); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName); + } + 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 = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); + } else { + value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + } + property = new ComponentInstanceInput(curPropertyDef, value, null); + String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); + property.setValue(validPropertyVAlue); + if (isNotEmpty(getInputs)) { + List getInputValues = new ArrayList<>(); + for (GetInputValueDataDefinition getInput : getInputs) { + List inputs = resource.getInputs(); + if (CollectionUtils.isEmpty(inputs)) { + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR Failed to add property: " + propName + " to resource instance: {}. Inputs list is empty ", + currentCompInstance.getUniqueId()); + log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, + currentCompInstance.getUniqueId()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + Optional optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + if (!optional.isPresent()) { + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR Failed to find input: " + getInput.getInputName()); + log.debug("Failed to find input {} ", getInput.getInputName()); + // @@TODO error message + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + InputDefinition input = optional.get(); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + processGetInput(getInputValues, inputs, getInputIndex); + } + property.setGetInputValues(getInputValues); + } + instPropList.add(property); + // delete overriden property + currPropertiesMap.remove(property.getName()); + } + + private void processGetInput(List getInputValues, List inputs, + GetInputValueDataDefinition getInputIndex) { + Optional optional; + 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 + throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); + } + InputDefinition inputIndex = optional.get(); + getInputIndex.setInputId(inputIndex.getUniqueId()); + getInputValues.add(getInputIndex); + } + } + + private void addInput(Map currPropertiesMap, InputDefinition prop) { + String propName = prop.getName(); + if (!currPropertiesMap.containsKey(propName)) { + currPropertiesMap.put(propName, prop); + } + } + + private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, + ComponentInstance currentCompInstance, 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())) { + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR Failed to find properties"); + log.debug("failed to find properties"); + return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); + } + 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); + loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR Failed to find property: {}", propName); + return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); + } + 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 = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); + } else { + value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + } + property = new ComponentInstanceProperty(curPropertyDef, value, null); + String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); + property.setValue(validatePropValue); + 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 instance. Inputs list is empty ", property); + loggerSupportability + .log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "Failed to add property: {} to instance. Inputs list is empty", propName); + rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, + property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString()); + } + Either inputEither = findInputByName(inputs, getInput); + if (inputEither.isRight()) { + throw inputEither.right().value(); + } else { + InputDefinition input = inputEither.left().value(); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + if (getInputIndex != null) { + Either newInputEither = findInputByName(inputs, getInputIndex); + if (inputEither.isRight()) { + throw newInputEither.right().value(); + } else { + InputDefinition newInput = newInputEither.left().value(); + getInputIndex.setInputId(newInput.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 findAvailableCapability(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 (isBoundedByOccurrences(cap)) { + String leftOccurrences = cap.getLeftOccurrences(); + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + } + } + return cap; + } + + private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) { + Map> capMap = instance.getCapabilities(); + if (capMap.containsKey(validReq.getCapability())) { + List capList = capMap.get(validReq.getCapability()); + for (CapabilityDefinition cap : capList) { + if (isBoundedByOccurrences(cap)) { + String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences(); + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + return cap; + } + } else { + return cap; + } + } + } + return null; + } + + private boolean isBoundedByOccurrences(CapabilityDefinition cap) { + return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES); + } + + 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); + } + + private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource, + Map uploadResInstancesMap, Map nodeNamespaceMap, + Map existingNodeTypesByResourceNames) { + Either eitherResource; + log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); + if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); + throw new ByResponseFormatComponentException(responseFormat); + } + if (MapUtils.isNotEmpty(nodeNamespaceMap)) { + nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v)); + } + Map resourcesInstancesMap = new HashMap<>(); + uploadResInstancesMap.values().forEach( + i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypesByResourceNames, resourcesInstancesMap)); + if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) { + Map existingNodeTypesByUids = existingNodeTypesByResourceNames.values().stream() + .collect(toMap(Resource::getUniqueId, r -> r)); + oldResource.getComponentInstances().stream().filter(i -> !i.isCreatedFromCsar()) + .forEach(uiInst -> resourcesInstancesMap.put(uiInst, getOriginResource(existingNodeTypesByUids, uiInst))); + } + if (isNotEmpty(resourcesInstancesMap)) { + try { + toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, oldResource != null); + } catch (StorageException exp) { + if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) { + log.debug("Failed to add component instances to container component {}", resource.getName()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus())); + eitherResource = Either.right(responseFormat); + throw new ByResponseFormatComponentException(eitherResource.right().value()); + } + } + } + if (CollectionUtils.isEmpty(resource.getComponentInstances()) && + resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances + log.debug("Error when create resource instance from csar. ComponentInstances list empty"); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty"); + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); + } + return resource; + } + + private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Resource resource, + Map nodeNamespaceMap, Map existingnodeTypeMap, + Map resourcesInstancesMap) { + Either eitherResource; + log.debug("*************Going to create resource instances {}", yamlName); + // 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()); + } + Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap, resource); + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setComponentUid(refResource.getUniqueId()); + Collection directives = uploadComponentInstanceInfo.getDirectives(); + if (directives != null && !directives.isEmpty()) { + componentInstance.setDirectives(new ArrayList<>(directives)); + } + UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo(); + if (uploadNodeFilterInfo != null) { + componentInstance + .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId())); + } + ComponentTypeEnum containerComponentType = resource.getComponentType(); + NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); + if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && isNotEmpty( + refResource.getCapabilities())) { + setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); + Map> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities( + refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); + componentInstance.setCapabilities(validComponentInstanceCapabilities); + } + if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) { + Map> artifacts = uploadComponentInstanceInfo.getArtifacts(); + Map toscaArtifacts = new HashMap<>(); + Map> arts = artifacts.entrySet().stream() + .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName())) + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + Map artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()); + for (Map.Entry entry : artifact.entrySet()) { + ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition(); + to.setFile(entry.getValue().getFile()); + to.setType(entry.getValue().getType()); + toscaArtifacts.put(entry.getKey(), to); + } + componentInstance.setToscaArtifacts(toscaArtifacts); + } + if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { + log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), + uploadComponentInstanceInfo.getType()); + } + Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); + componentInstance.setName(uploadComponentInstanceInfo.getName()); + componentInstance.setIcon(origResource.getIcon()); + componentInstance.setCreatedFrom(CreatedFrom.CSAR); + resourcesInstancesMap.put(componentInstance, origResource); + } + + 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 Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, + Map nodeNamespaceMap, Resource resource) { + log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + Resource refResource; + if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { + refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); + } else { + Either findResourceEither = toscaOperationFacade + .getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(), + ((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease()); + if (findResourceEither.isRight()) { + log.debug("validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); + } + 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); + throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), + refResource.getName(), componentState); + } + if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) { + log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), + uploadComponentInstanceInfo.getType()); + } + return refResource; + } + + public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, + boolean needLock, boolean forceCertificationAllowed) { + boolean failed = false; + try { + if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic + .isFirstCertification(resource.getVersion())) { + nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); + } + if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { + Either eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock, false); + return resource; + } + return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); + } catch (ComponentException e) { + failed = true; + log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e); + throw e; + } finally { + if (failed) { + BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); + if (!inTransaction) { + janusGraphDao.rollback(); + } + } else if (!inTransaction) { + janusGraphDao.commit(); + } + } + } + + private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, + boolean needLock) { + Either resourceResponse = lifecycleBusinessLogic + .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock); + if (resourceResponse.isRight()) { + throw new ByResponseFormatComponentException(resourceResponse.right().value()); + } + return resourceResponse.left().value(); + } + + private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, + boolean needLock) { + return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); + } + + public ImmutablePair createOrUpdateResourceByImport(final Resource resource, final User user, final boolean isNormative, + final boolean isInTransaction, final boolean needLock, + final CsarInfo csarInfo, final String nodeName, + final boolean isNested) { + ImmutablePair result = null; + // check if resource already exists (search by tosca name = type) + final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName); + final Either latestByToscaName = toscaOperationFacade + .getLatestByToscaResourceName(resource.getToscaResourceName()); + if (latestByToscaName.isLeft()) { + Resource foundResource = latestByToscaName.left().value(); + // we don't allow updating names of top level types + if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) { + BeEcompErrorManager.getInstance() + .logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + log.debug("resource already exist new name={} old name={} same type={}", resource.getName(), foundResource.getName(), + resource.getToscaResourceName()); + final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + throwComponentException(responseFormat); + } + result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested); + } else if (isNotFound(latestByToscaName)) { + if (isNestedResource) { + result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName); + } else { + result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } + } else { + StorageOperationStatus status = latestByToscaName.right().value(); + log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + throwComponentException(responseFormat); + } + return result; + } + + private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) { + return csarInfo != null && csarInfo.isUpdate() && nodeName != null; + } + + private ImmutablePair createOrUpdateNestedResource(final Resource resource, final User user, final boolean isNormative, + final boolean isInTransaction, final boolean needLock, + final CsarInfo csarInfo, final boolean isNested, + final String nodeName) { + final Either latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName( + buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight()); + if (latestByToscaName.isLeft()) { + final Resource nestedResource = (Resource) latestByToscaName.left().value(); + log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); + final Either eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource, + ValidationUtils.hasBeenCertified(nestedResource.getVersion())); + if (eitherValidation.isRight()) { + return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } + return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested); + } else { + return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } + } + + private boolean isNotFound(Either getResourceEither) { + return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND; + } + + private ImmutablePair createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, + CsarInfo csarInfo) { + log.debug("resource with name {} does not exist. create new resource", resource.getName()); + validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo); + final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction); + Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value(); + ImmutablePair resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED); + ASDCKpiApi.countImportResourcesKPI(); + return resourcePair; + } + + public boolean isResourceExist(String resourceName) { + Either latestByName = toscaOperationFacade.getLatestByName(resourceName); + return latestByName.isLeft(); + } + + private ImmutablePair 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()); + ImmutablePair resourcePair = null; + try { + lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import"); + oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false); + mergeOldResourceMetadataWithNew(oldResource, newResource); + validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); + validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction); + // contact info normalization + newResource.setContactId(newResource.getContactId().toLowerCase()); + PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource); + // 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 (CollectionUtils.isEmpty(newResource.getDerivedFrom())) { + newResource.setDerivedFrom(oldResource.getDerivedFrom()); + } + if (CollectionUtils.isEmpty(newResource.getDataTypes())) { + newResource.setDataTypes(oldResource.getDataTypes()); + } + if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())) { + newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType()); + } + if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())) { + newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion()); + } + // add for new) + + // created without tosca artifacts - add the placeholders + if (MapUtils.isEmpty(newResource.getToscaArtifacts())) { + setToscaArtifactsPlaceHolders(newResource, user); + } + if (MapUtils.isEmpty(newResource.getInterfaces())) { + newResource.setInterfaces(oldResource.getInterfaces()); + } + if (CollectionUtils.isEmpty(newResource.getAttributes())) { + newResource.setAttributes(oldResource.getAttributes()); + } + if (CollectionUtils.isEmpty(newResource.getProperties())) { + newResource.setProperties(oldResource.getProperties()); + } + 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); + throwComponentException(responseFormat); + } + updateCatalog(overrideResource.left().value(), ChangeTypeEnum.LIFECYCLE); + log.debug("Resource updated successfully!!!"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, + ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build()); + resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK); + return resourcePair; + } finally { + if (resourcePair == null) { + BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); + janusGraphDao.rollback(); + } else if (!inTransaction) { + janusGraphDao.commit(); + } + if (needLock) { + 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()); + } + List oldForUpdate = oldResource.getGroups(); + if (CollectionUtils.isNotEmpty(oldForUpdate)) { + List groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList()); + groupForUpdate.stream().filter(group -> group.isVspOriginated()).forEach(group -> group.setName(group.getInvariantName())); + newResource.setGroups(groupForUpdate); + } + if (newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root") + && newResource.getResourceType() != ResourceTypeEnum.CVFC) { + ResourceTypeEnum updatedResourceType = newResource.getResourceType(); + Component derivedFromResource = getParentComponent(newResource); + if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) { + Resource parentResource = (Resource) derivedFromResource; + if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() + || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) && parentResource.getResourceType() != updatedResourceType + && oldResource.getResourceType() != updatedResourceType) { + BeEcompErrorManager.getInstance().logInternalDataError("mergeOldResourceMetadataWithNew", + "resource type of the resource does not match to derived from resource type", ErrorSeverity.ERROR); + log.debug( + "#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}", + newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType()); + throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE); + } + } + } + } + + private Component getParentComponent(Resource newResource) { + String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0); + Either latestByToscaResourceName = toscaOperationFacade + .getLatestByToscaResourceName(toscaResourceNameDerivedFrom); + if (latestByToscaResourceName.isRight()) { + BeEcompErrorManager.getInstance() + .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR); + log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom); + } + return latestByToscaResourceName.left().value(); + } + + private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) { + if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) { + // checkout + return lifecycleBusinessLogic + .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), + inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource)); + } + return oldResource; + } + + private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) { + log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage()); + componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, + ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build()); + throw new ByResponseFormatComponentException(response); + } + + public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, + CsarInfo csarInfo) { + validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction); + validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction); + validateLifecycleTypesCreate(user, resource, actionEnum); + validateResourceType(user, resource, actionEnum); + 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 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_VALIDATE_CAPABILITY_TYPES, "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_VALIDATE_CAPABILITY_TYPES); + } + 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_VALIDATE_CAPABILITY_TYPES, "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_VALIDATE_CAPABILITY_TYPES); + } + 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()); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + return Either.right(errorResponse); + } + CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); + if (capabilityTypeDefinition.getProperties() != null) { + for (CapabilityDefinition capDef : typeEntry.getValue()) { + List properties = capDef.getProperties(); + List changedProperties = new ArrayList<>(); + if (properties == null || properties.isEmpty()) { + for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { + ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); + changedProperties.add(newProp); + } + } else { + List propsToAdd = new ArrayList<>(); + for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { + PropertyDefinition propFromDef = prop.getValue(); + boolean propFound = false; + for (ComponentInstanceProperty cip : properties) { + if (propFromDef.getName().equals(cip.getName())) { + //merge property value and property description only, ignore other fields + if (cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())) { + propFromDef.setDescription(cip.getDescription()); + } + propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>()); + if (cip.getValue() != null) { + propFromDef.setValue(cip.getValue()); + } + propsToAdd.add(new ComponentInstanceProperty(propFromDef)); + propFound = true; + properties.remove(cip); + break; + } + } + if (!propFound) { + propsToAdd.add(new ComponentInstanceProperty(propFromDef)); + } + } + if (!propsToAdd.isEmpty()) { + changedProperties.addAll(propsToAdd); + } + } + capDef.setProperties(changedProperties); + } + } + return eitherResult; + } + + public Resource 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 + Resource createdResource = null; + if (!inTransaction) { + Either lockResult = lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByResponseFormatComponentException(responseFormat); + } + log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); + } + try { + if (resource.deriveFromGeneric()) { + handleResourceGenericType(resource); + } + createdResource = createResourceTransaction(resource, user, isNormative); + componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user, createdResource, actionEnum); + ASDCKpiApi.countCreatedResourcesKPI(); + } catch (ComponentException e) { + ResponseFormat responseFormat = + e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw e; + } catch (StorageException e) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw e; + } finally { + if (!inTransaction) { + graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); + } + } + return createdResource; + } + + private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) { + // validate resource name uniqueness + log.debug("validate resource name"); + Either eitherValidation = toscaOperationFacade + .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); + if (eitherValidation.isRight()) { + loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "ERROR while validate component name {} Status is: {}", resource.getName(), eitherValidation.right().value()); + log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value()); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); + } + if (eitherValidation.left().value()) { + log.debug("resource with name: {}, already exists", resource.getName()); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR, + "resource with name: {} already exists", resource.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), + resource.getName()); + } + 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); + } + } + return toscaOperationFacade.createToscaComponent(resource).left().on(r -> throwComponentExceptionByResource(r, resource)); + } + + private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource); + throw new ByResponseFormatComponentException(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) { + Map finalArtifactMap = artifactMap; + deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v)); + } + resource.setDeploymentArtifacts(artifactMap); + } + + private void processDeploymentResourceArtifacts(User user, Resource resource, Map artifactMap, String k, Object v) { + Map artifactDetails = (Map) v; + Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES); + if (object != null) { + List artifactTypes = (List) object; + if (!artifactTypes.contains(resource.getResourceType().name())) { + return; + } + } else { + log.info("resource types for artifact placeholder {} were not defined. default is all resources", k); + } + if (artifactsBusinessLogic != null) { + ArtifactDefinition artifactDefinition = artifactsBusinessLogic + .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map) v, user, ArtifactGroupTypeEnum.DEPLOYMENT); + if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + } + } + } + + @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(); + isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category)); + } + if (isCreateArtifact && exludeResourceType != null) { + String resourceType = resource.getResourceType().name(); + isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType)); + } + 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; + validateUserExists(user); + 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; + lockComponent(resourceId, resource, "Mark resource to delete"); + try { + result = markComponentToDelete(resource); + if (result == 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 != StorageOperationStatus.OK) { + janusGraphDao.rollback(); + } else { + janusGraphDao.commit(); + } + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + } + + public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + validateUserExists(user); + Resource resource = null; + StorageOperationStatus result = StorageOperationStatus.OK; + boolean failed = false; + 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 { + janusGraphDao.commit(); + } + if (resource != null) { + lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE); + try { + result = markComponentToDelete(resource); + if (result != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); + return responseFormat; + } + } catch (ComponentException e) { + failed = true; + throw e; + } finally { + if (failed || result == null || result != StorageOperationStatus.OK) { + janusGraphDao.rollback(); + } else { + janusGraphDao.commit(); + } + graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); + } + } + return responseFormat; + } + + public Either getResource(String resourceId, User user) { + if (user != null) { + validateUserExists(user); + } + 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) { + validateUserExists(userId); + 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 Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, + boolean inTransaction) { + validateUserExists(user.getUserId()); + log.debug("Get resource with id {}", resourceIdToUpdate); + boolean needToUnlock = false; + try { + if (currentResource == null) { + Either storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate); + if (storageStatus.isRight()) { + throw new ByResponseFormatComponentException( + 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())) { + throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + // lock resource + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); + if (lockResult != 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)); + throw new ByResponseFormatComponentException(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 - property.setValue(validPropertyVAlue); - - if (isNotEmpty(getInputs)) { - List getInputValues = new ArrayList<>(); - for (GetInputValueDataDefinition getInput : getInputs) { - List inputs = resource.getInputs(); - if (CollectionUtils.isEmpty(inputs)) { - loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId()); - log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, - currentCompInstance.getUniqueId()); - throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); - } - - Optional optional = inputs.stream() - .filter(p -> p.getName() - .equals(getInput.getInputName())) - .findAny(); - if (!optional.isPresent()) { - loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName()); - log.debug("Failed to find input {} ", getInput.getInputName()); - // @@TODO error message - throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); - } - InputDefinition input = optional.get(); - getInput.setInputId(input.getUniqueId()); - getInputValues.add(getInput); - - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - processGetInput(getInputValues, inputs, getInputIndex); - } - property.setGetInputValues(getInputValues); - } - instPropList.add(property); - // delete overriden property - currPropertiesMap.remove(property.getName()); - } - - private void processGetInput(List getInputValues, List inputs, - GetInputValueDataDefinition getInputIndex) { - Optional optional; - 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 - throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT); - } - InputDefinition inputIndex = optional.get(); - getInputIndex.setInputId(inputIndex.getUniqueId()); - getInputValues.add(getInputIndex); - } - } - - private void addInput(Map currPropertiesMap, InputDefinition prop) { - String propName = prop.getName(); - if (!currPropertiesMap.containsKey(propName)) { - currPropertiesMap.put(propName, prop); - } - } - - private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, - Resource resource, Resource originResource, ComponentInstance currentCompInstance, - 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())) { - loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR Failed to find properties"); - log.debug("failed to find properties"); - return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); - } - 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); - loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName); - return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); - } - 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 = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); - } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - } - property = new ComponentInstanceProperty(curPropertyDef, value, null); + // VF "derivedFrom" should be null (or ignored) + if (ModelConverter.isAtomicComponent(currentResource)) { + validateDerivedFromNotEmpty(null, newResource, null); + validateDerivedFromNotEmpty(null, currentResource, null); + } else { + newResource.setDerivedFrom(null); + } + Either dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, + true); + if (dataModelResponse.isRight()) { + log.debug("failed to update resource metadata!!!"); + throw new ByResponseFormatComponentException(dataModelResponse.right().value()); + } + log.debug("Resource metadata updated successfully!!!"); + return dataModelResponse.left().value(); + } catch (ComponentException | StorageException e) { + rollback(inTransaction, newResource, null, null); + throw e; + } finally { + if (!inTransaction) { + janusGraphDao.commit(); + } + if (needToUnlock) { + graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); + } + } + } - String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); - property.setValue(validatePropValue); + private Either updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, + Resource currentResource, boolean shouldLock, boolean inTransaction) { + updateVfModuleGroupsNames(currentResource, newResource); + validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false); + // 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(), + 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 (isNotEmpty(newResource.getGroups())) { + for (GroupDefinition group : newResource.getGroups()) { + if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) { + groupBusinessLogic + .validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(), user, + newResource.getComponentType(), 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()); + } - 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 instance. Inputs list is empty ", property); - loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName); - rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() - .stream() - .map(GetInputValueDataDefinition::getInputName) - .collect(toList()) - .toString()); - } - Either inputEither = findInputByName(inputs, getInput); - if (inputEither.isRight()) { - throw inputEither.right().value(); - } else { - InputDefinition input = inputEither.left().value(); - getInput.setInputId(input.getUniqueId()); - getInputValues.add(getInput); - - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - if (getInputIndex != null) { - Either newInputEither = findInputByName(inputs, - getInputIndex); - if (inputEither.isRight()) { - throw newInputEither.right().value(); - } else { - InputDefinition newInput = newInputEither.left().value(); - getInputIndex.setInputId(newInput.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 findAvailableCapability(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 (isBoundedByOccurrences(cap)) { - String leftOccurrences = cap.getLeftOccurrences(); - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - cap.setLeftOccurrences(String.valueOf(left)); - - } - - } - return cap; - } - - private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) { - Map> capMap = instance.getCapabilities(); - if (capMap.containsKey(validReq.getCapability())) { - List capList = capMap.get(validReq.getCapability()); - - for (CapabilityDefinition cap : capList) { - if (isBoundedByOccurrences(cap)) { - String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() - : cap.getMaxOccurrences(); - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - cap.setLeftOccurrences(String.valueOf(left)); - return cap; - } - } else { - return cap; - } - } - } - return null; - } - - private boolean isBoundedByOccurrences(CapabilityDefinition cap) { - return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences() - .equals(CapabilityDataDefinition.MAX_OCCURRENCES); - } - - 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); - } - - private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource, - Map uploadResInstancesMap, Map nodeNamespaceMap, Map existingNodeTypesByResourceNames) { - - Either eitherResource; - log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); - if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); - throw new ByResponseFormatComponentException(responseFormat); - } - if (MapUtils.isNotEmpty(nodeNamespaceMap)) { - nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v)); - } - Map resourcesInstancesMap = new HashMap<>(); - uploadResInstancesMap.values() - .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, - existingNodeTypesByResourceNames, resourcesInstancesMap)); - if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) { - Map existingNodeTypesByUids = existingNodeTypesByResourceNames.values() - .stream() - .collect(toMap(Resource::getUniqueId, r -> r)); - oldResource.getComponentInstances() - .stream() - .filter(i -> !i.isCreatedFromCsar()) - .forEach(uiInst -> resourcesInstancesMap.put(uiInst, - getOriginResource(existingNodeTypesByUids, uiInst))); - } - - if (isNotEmpty(resourcesInstancesMap)) { - try { - toscaOperationFacade.associateComponentInstancesToComponent(resource, - resourcesInstancesMap, false, oldResource != null); - } catch (StorageException exp) { - if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) { - log.debug("Failed to add component instances to container component {}", resource.getName()); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus())); - eitherResource = Either.right(responseFormat); - throw new ByResponseFormatComponentException(eitherResource.right().value()); - } - } - } - if (CollectionUtils.isEmpty(resource.getComponentInstances()) && - resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances - log.debug("Error when create resource instance from csar. ComponentInstances list empty"); - BeEcompErrorManager.getInstance() - .logBeDaoSystemError( - "Error when create resource instance from csar. ComponentInstances list empty"); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); - } - return resource; - } - - private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, - Resource resource, Map nodeNamespaceMap, Map existingnodeTypeMap, - Map resourcesInstancesMap) { - Either eitherResource; - log.debug("*************Going to create resource instances {}", yamlName); - // 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()); - } - Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, - existingnodeTypeMap, resource); - - ComponentInstance componentInstance = new ComponentInstance(); - componentInstance.setComponentUid(refResource.getUniqueId()); - Collection directives = uploadComponentInstanceInfo.getDirectives(); - if(directives != null && !directives.isEmpty()) { - componentInstance.setDirectives(new ArrayList<>(directives)); + private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) { + if (currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())) { + List updatedGroups = currentResource.getGroups().stream() + .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName())).collect(toList()); + newResource.setGroups(updatedGroups); } - UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo(); - if (uploadNodeFilterInfo != null){ - componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, - componentInstance.getUniqueId())); + } + + private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) { + GroupDefinition updatedGroup = new GroupDefinition(currGroup); + if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(DEFAULT_GROUP_VF_MODULE)) { + String prefix = updatedGroup.getName().substring(0, replacePattern.length()); + String newGroupName = updatedGroup.getName().replaceFirst(prefix, with); + updatedGroup.setName(newGroupName); } - ComponentTypeEnum containerComponentType = resource.getComponentType(); - NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); - if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) - && isNotEmpty(refResource.getCapabilities())) { - setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); - Map> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities( - refResource.getUniqueId(), refResource.getCapabilities(), - uploadComponentInstanceInfo.getCapabilities()); - componentInstance.setCapabilities(validComponentInstanceCapabilities); - } + return updatedGroup; + } - if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) { - Map> artifacts = uploadComponentInstanceInfo.getArtifacts(); - Map toscaArtifacts = new HashMap<>(); - Map> arts = artifacts.entrySet().stream() - .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName())) - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - Map artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()); - for (Map.Entry entry : artifact.entrySet()) { - ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition(); - to.setFile(entry.getValue().getFile()); - to.setType(entry.getValue().getType()); - toscaArtifacts.put(entry.getKey(), to); + /** + * validateResourceFieldsBeforeCreate + * + * @param user - modifier data (userId) + */ + private void validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { + componentValidator.validate(user, resource, actionEnum); + // validate category + log.debug("validate category"); + validateCategory(user, resource, actionEnum, inTransaction); + // validate vendor name & release & model number + log.debug("validate vendor name"); + validateVendorName(user, resource, actionEnum); + log.debug("validate vendor release"); + validateVendorReleaseName(user, resource, actionEnum); + log.debug("validate resource vendor model number"); + validateResourceVendorModelNumber(user, resource, actionEnum); + // validate cost + log.debug("validate cost"); + validateCost(resource); + // validate licenseType + log.debug("validate licenseType"); + validateLicenseType(user, resource, actionEnum); + // validate template (derived from) + log.debug("validate derived from"); + if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) { + resource.setDerivedFrom(null); + } + validateDerivedFromExist(user, resource, actionEnum); + // warn about non-updatable fields + checkComponentFieldsForOverrideAttempt(resource); + String currentCreatorFullName = resource.getCreatorFullName(); + if (currentCreatorFullName != null) { + log.debug("Resource Creator fullname is automatically set and cannot be updated"); + } + String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); + if (currentLastUpdaterFullName != null) { + log.debug("Resource LastUpdater fullname is automatically set and cannot be updated"); + } + Long currentLastUpdateDate = resource.getLastUpdateDate(); + if (currentLastUpdateDate != null) { + log.debug("Resource last update date is automatically set and cannot be updated"); + } + Boolean currentAbstract = resource.isAbstract(); + if (currentAbstract != null) { + log.debug("Resource abstract is automatically set and cannot be updated"); + } + } + + /** + * validateResourceFieldsBeforeUpdate + * + * @param currentResource - Resource object to validate + * @param isNested + */ + private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) { + validateFields(currentResource, updateInfoResource, inTransaction, isNested); + warnNonEditableFields(currentResource, updateInfoResource); + } + + private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) { + String currentResourceVersion = currentResource.getVersion(); + String updatedResourceVersion = updateInfoResource.getVersion(); + if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) { + log.debug("Resource version is automatically set and cannot be updated"); + } + String currentCreatorUserId = currentResource.getCreatorUserId(); + String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); + if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { + log.debug("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.debug("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.debug("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.debug("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.debug("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.debug("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.debug("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.debug("Resource abstract is automatically set and cannot be updated"); + } + Boolean currentHighestVersion = currentResource.isHighestVersion(); + Boolean updatedHighestVersion = updateInfoResource.isHighestVersion(); + if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) { + log.debug("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.debug("Resource UUID is automatically set and cannot be updated"); + } + log.debug("Resource Type cannot be updated"); + String currentInvariantUuid = currentResource.getInvariantUUID(); + String updatedInvariantUuid = updateInfoResource.getInvariantUUID(); + if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { + log.debug("Resource invariant UUID is automatically set and cannot be updated"); + updateInfoResource.setInvariantUUID(currentInvariantUuid); + } + } + + private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) { + boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); + log.debug("validate resource name before update"); + validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested); + log.debug("validate description before update"); + componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null); + log.debug("validate icon before update"); + validateIcon(currentResource, updateInfoResource, hasBeenCertified); + log.debug("validate tags before update"); + componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null); + log.debug("validate vendor name before update"); + validateVendorName(null, updateInfoResource, null); + log.debug("validate resource vendor model number before update"); + validateResourceVendorModelNumber(currentResource, updateInfoResource); + log.debug("validate vendor release before update"); + validateVendorReleaseName(null, updateInfoResource, null); + log.debug("validate contact info before update"); + componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null); + log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); + validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified); + log.debug("validate category before update"); + validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction); + } + + 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() == ResourceTypeEnum.CVFC && resourceNameUpdated + .equals(addCvfcSuffixToResourceName(resourceNameCurrent)); + } + + private String addCvfcSuffixToResourceName(String resourceName) { + return resourceName + "Cvfc"; + } + + private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) { + String resourceNameUpdated = updateInfoResource.getName(); + if (!isResourceNameEquals(currentResource, updateInfoResource)) { + if (isNested || !hasBeenCertified) { + componentNameValidator.validateAndCorrectField(null, updateInfoResource, null); + validateResourceNameUniqueness(updateInfoResource); + 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); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); } - componentInstance.setToscaArtifacts(toscaArtifacts); } + } - if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { - log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", - uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - } - Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); - componentInstance.setName(uploadComponentInstanceInfo.getName()); - componentInstance.setIcon(origResource.getIcon()); - componentInstance.setCreatedFrom(CreatedFrom.CSAR); - resourcesInstancesMap.put(componentInstance, origResource); - } - - 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 Resource validateResourceInstanceBeforeCreate(String yamlName, - UploadComponentInstanceInfo uploadComponentInstanceInfo, Map nodeNamespaceMap, Resource resource) { - - log.debug( - "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create", - uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - Resource refResource; - if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { - refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); - } else { - Either findResourceEither = toscaOperationFacade - .getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(), - ((ResourceMetadataDataDefinition)resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease()); - if (findResourceEither.isRight()) { - log.debug( - "validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}", - uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); - } - 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); - throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, - refResource.getComponentType().getValue(),refResource.getName(), componentState); - } - - if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) { - log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); - throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - } - return refResource; - } - - public Resource propagateStateToCertified(User user, Resource resource, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, - boolean forceCertificationAllowed) { - - boolean failed = false; - try { - if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed - && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) { - nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); - } - if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { - Either eitherPopulated = populateToscaArtifacts( - resource, user, false, inTransaction, needLock, false); - return resource; - } - return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); - } catch (ComponentException e) { - failed = true; - log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e); - throw e; - } finally { - if (failed) { - BeEcompErrorManager.getInstance() - .logBeSystemError("Change LifecycleState - Certify"); - if (!inTransaction) { - janusGraphDao.rollback(); - } - } else if (!inTransaction) { - janusGraphDao.commit(); - } - } - } - - private Resource nodeFullCertification(String uniqueId, User user, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - Either resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, - inTransaction, needLock); - if(resourceResponse.isRight()){ - throw new ByResponseFormatComponentException(resourceResponse.right().value()); - } - return resourceResponse.left().value(); - } - - private Resource nodeForceCertification(Resource resource, User user, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, - needLock); - } - - public ImmutablePair createOrUpdateResourceByImport(final Resource resource, - final User user, - final boolean isNormative, - final boolean isInTransaction, - final boolean needLock, - final CsarInfo csarInfo, - final String nodeName, - final boolean isNested) { - - ImmutablePair result = null; - // check if resource already exists (search by tosca name = type) - final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName); - final Either latestByToscaName = toscaOperationFacade - .getLatestByToscaResourceName(resource.getToscaResourceName()); - - if (latestByToscaName.isLeft()) { - Resource foundResource = latestByToscaName.left().value(); - // we don't allow updating names of top level types - if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) { - BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", - ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - log.debug("resource already exist new name={} old name={} same type={}", resource.getName(), - foundResource.getName(), resource.getToscaResourceName()); - final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); - componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); - throwComponentException(responseFormat); - } - result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested); - } else if (isNotFound(latestByToscaName)) { - if (isNestedResource) { - result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, - isNested, nodeName); - } else { - result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } - } else { - StorageOperationStatus status = latestByToscaName.right().value(); - log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils - .convertFromStorageResponse(latestByToscaName.right().value()), resource); - componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); - throwComponentException(responseFormat); - } - return result; - } - - private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) { - return csarInfo != null && csarInfo.isUpdate() && nodeName != null; - } - - private ImmutablePair createOrUpdateNestedResource(final Resource resource, - final User user, - final boolean isNormative, - final boolean isInTransaction, - final boolean needLock, - final CsarInfo csarInfo, - final boolean isNested, - final String nodeName) { - final Either latestByToscaName = toscaOperationFacade - .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType() - .name(), csarInfo.getVfResourceName(), nodeName).getRight()); - if (latestByToscaName.isLeft()) { - final Resource nestedResource = (Resource) latestByToscaName.left().value(); - log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); - final Either eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, - resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion())); - if (eitherValidation.isRight()) { - return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } - return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested); - } else { - return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } - } - - private boolean isNotFound(Either getResourceEither) { - return getResourceEither.isRight() && getResourceEither.right() - .value() == StorageOperationStatus.NOT_FOUND; - } - - private ImmutablePair createResourceByImport(Resource resource, User user, - boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) { - log.debug("resource with name {} does not exist. create new resource", resource.getName()); - validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo); - final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, - isInTransaction); - Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value(); - ImmutablePair resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED); - ASDCKpiApi.countImportResourcesKPI(); - return resourcePair; - } - - public boolean isResourceExist(String resourceName) { - Either latestByName = toscaOperationFacade.getLatestByName(resourceName); - return latestByName.isLeft(); - } - - private ImmutablePair 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()); - ImmutablePair resourcePair = null; - try { - lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import"); - oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false); - mergeOldResourceMetadataWithNew(oldResource, newResource); - - validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); - validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction); - // contact info normalization - newResource.setContactId(newResource.getContactId().toLowerCase()); - PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource); - // 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 (CollectionUtils.isEmpty(newResource.getDerivedFrom())){ - newResource.setDerivedFrom(oldResource.getDerivedFrom()); - } - if (CollectionUtils.isEmpty(newResource.getDataTypes())){ - newResource.setDataTypes(oldResource.getDataTypes()); - } - if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())){ - newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType()); - } - if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())){ - newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion()); - } - // add for new) - // created without tosca artifacts - add the placeholders - if (MapUtils.isEmpty(newResource.getToscaArtifacts())){ - setToscaArtifactsPlaceHolders(newResource, user); - } - - if (MapUtils.isEmpty(newResource.getInterfaces())){ - newResource.setInterfaces(oldResource.getInterfaces()); - } - if (CollectionUtils.isEmpty(newResource.getAttributes())) { - newResource.setAttributes(oldResource.getAttributes()); - } - - if (CollectionUtils.isEmpty(newResource.getProperties())) { - newResource.setProperties(oldResource.getProperties()); - } - - 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); - - throwComponentException(responseFormat); - } - updateCatalog(overrideResource.left() - .value(), ChangeTypeEnum.LIFECYCLE); - - log.debug("Resource updated successfully!!!"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, - ResourceVersionInfo.newBuilder() - .state(oldResource.getLifecycleState() - .name()) - .version(oldResource.getVersion()) - .build()); - - resourcePair = new ImmutablePair<>(overrideResource.left() - .value(), ActionStatus.OK); - return resourcePair; - } finally { - if (resourcePair == null) { - BeEcompErrorManager.getInstance() - .logBeSystemError("Change LifecycleState - Certify"); - janusGraphDao.rollback(); - } else if (!inTransaction) { - janusGraphDao.commit(); - } - if (needLock) { - 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()); - } - ListoldForUpdate = oldResource.getGroups(); - if(CollectionUtils.isNotEmpty(oldForUpdate)){ - ListgroupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList()); - - groupForUpdate.stream().filter(group -> group.isVspOriginated()) - .forEach(group -> group.setName(group.getInvariantName())); - - newResource.setGroups(groupForUpdate); - } - - - if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) { - ResourceTypeEnum updatedResourceType = newResource.getResourceType(); - Component derivedFromResource = getParentComponent(newResource); - if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) { - Resource parentResource = (Resource) derivedFromResource; - if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) && - parentResource.getResourceType() != updatedResourceType && oldResource.getResourceType() != updatedResourceType) { - BeEcompErrorManager.getInstance() - .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type", - ErrorSeverity.ERROR); - log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}", - newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType()); - throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE); - } - } - } - - } - - private Component getParentComponent(Resource newResource) { - String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0); - Either latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom); - if(latestByToscaResourceName.isRight()){ - BeEcompErrorManager.getInstance() - .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR); - log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom); - } - return latestByToscaResourceName.left().value(); - } - - private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, - boolean inTransaction, boolean needLock) { - - if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) { - // checkout - return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, - new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock) - .left() - .on(response -> failOnChangeState(response, user, oldResource, newResource)); - } - return oldResource; - } - - private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) { - log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage()); - componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, - ResourceVersionInfo.newBuilder() - .state(oldResource.getLifecycleState() - .name()) - .version(oldResource.getVersion()) - .build()); - throw new ByResponseFormatComponentException(response); - } - - public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, - boolean inTransaction, CsarInfo csarInfo) { - - validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction); - validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction); - validateLifecycleTypesCreate(user, resource, actionEnum); - validateResourceType(user, resource, actionEnum); - 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 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_VALIDATE_CAPABILITY_TYPES, "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_VALIDATE_CAPABILITY_TYPES); - } - 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_VALIDATE_CAPABILITY_TYPES, "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_VALIDATE_CAPABILITY_TYPES); - } - 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()); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - return Either.right(errorResponse); - } - CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); - if (capabilityTypeDefinition.getProperties() != null) { - for (CapabilityDefinition capDef : typeEntry.getValue()) { - List properties = capDef.getProperties(); - List changedProperties = new ArrayList<>(); - if (properties == null || properties.isEmpty()) { - for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { - ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); - changedProperties.add(newProp); - } - } else { - List propsToAdd = new ArrayList<>(); - for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { - PropertyDefinition propFromDef = prop.getValue(); - boolean propFound = false; - for (ComponentInstanceProperty cip : properties) { - if (propFromDef.getName().equals(cip.getName())) { - //merge property value and property description only, ignore other fields - if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){ - propFromDef.setDescription(cip.getDescription()); - } - propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>()); - if(cip.getValue() != null){ - propFromDef.setValue(cip.getValue()); - } - propsToAdd.add(new ComponentInstanceProperty(propFromDef)); - propFound = true; - properties.remove(cip); - break; - } - } - if(!propFound) { - propsToAdd.add(new ComponentInstanceProperty(propFromDef)); - } - } - if (!propsToAdd.isEmpty()) { - changedProperties.addAll(propsToAdd); - } - } - capDef.setProperties(changedProperties); - } - } - return eitherResult; - } - - public Resource 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 - Resource createdResource = null; - if (!inTransaction) { - Either lockResult = lockComponentByName(resource.getSystemName(), resource, - CREATE_RESOURCE); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByResponseFormatComponentException(responseFormat); - } - - log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); - } - try { - if (resource.deriveFromGeneric()) { - handleResourceGenericType(resource); - } - createdResource = createResourceTransaction(resource, user, isNormative); - componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user, - createdResource, actionEnum); - ASDCKpiApi.countCreatedResourcesKPI(); - } catch (ComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat() == null - ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw e; - } catch (StorageException e) { - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw e; - } finally { - if (!inTransaction) { - graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), - NodeTypeEnum.Resource); - } - } - return createdResource; - } - - private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) { - // validate resource name uniqueness - log.debug("validate resource name"); - Either eitherValidation = toscaOperationFacade.validateComponentNameExists( - resource.getName(), resource.getResourceType(), resource.getComponentType()); - if (eitherValidation.isRight()) { - loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value()); - log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), - eitherValidation.right() - .value()); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right() - .value())); - } - if (eitherValidation.left() - .value()) { - log.debug("resource with name: {}, already exists", resource.getName()); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), - StatusCode.ERROR,"resource with name: {} already exists",resource.getName()); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, - ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - } - - 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); - } - } - return toscaOperationFacade.createToscaComponent(resource) - .left() - .on(r -> throwComponentExceptionByResource(r, resource)); - } - - private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) { - ResponseFormat responseFormat = componentsUtils - .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource); - throw new ByResponseFormatComponentException(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) { - Map finalArtifactMap = artifactMap; - deploymentResourceArtifacts - .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v)); - } - resource.setDeploymentArtifacts(artifactMap); - } - - private void processDeploymentResourceArtifacts(User user, Resource resource, - Map artifactMap, String k, Object v) { - Map artifactDetails = (Map) v; - Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES); - if (object != null) { - List artifactTypes = (List) object; - if (!artifactTypes.contains(resource.getResourceType() - .name())) { - return; - } - } else { - log.info("resource types for artifact placeholder {} were not defined. default is all resources", k); - } - if (artifactsBusinessLogic != null) { - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resource.getUniqueId(), k, (Map) v, user, ArtifactGroupTypeEnum.DEPLOYMENT); - if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } - } - } - - @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(); - isCreateArtifact = exludeResourceCategory.stream() - .noneMatch(e -> e.equalsIgnoreCase(category)); - } - if (isCreateArtifact && exludeResourceType != null) { - String resourceType = resource.getResourceType() - .name(); - isCreateArtifact = exludeResourceType.stream() - .noneMatch(e -> e.equalsIgnoreCase(resourceType)); - } - 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; - validateUserExists(user); - - 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; - lockComponent(resourceId, resource, "Mark resource to delete"); - try { - - result = markComponentToDelete(resource); - if (result == 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 != StorageOperationStatus.OK) { - janusGraphDao.rollback(); - } else { - janusGraphDao.commit(); - } - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - validateUserExists(user); - Resource resource = null; - StorageOperationStatus result = StorageOperationStatus.OK; - boolean failed = false; - 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 { - janusGraphDao.commit(); - } - if (resource != null) { - lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE); - try { - result = markComponentToDelete(resource); - if (result != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); - return responseFormat; - } - }catch (ComponentException e){ - failed = true; - throw e; - }finally { - if (failed || result == null || result != StorageOperationStatus.OK) { - janusGraphDao.rollback(); - } else { - janusGraphDao.commit(); - } - graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); - } - } - return responseFormat; - } - - public Either getResource(String resourceId, User user) { - - if (user != null) { - validateUserExists(user); - } - - 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) { - - validateUserExists(userId); - - 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 Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, - User user, boolean inTransaction) { - - validateUserExists(user.getUserId()); - - log.debug("Get resource with id {}", resourceIdToUpdate); - boolean needToUnlock = false; - - try { - if (currentResource == null) { - Either storageStatus = toscaOperationFacade - .getToscaElement(resourceIdToUpdate); - if (storageStatus.isRight()) { - throw new ByResponseFormatComponentException(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())) { - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // lock resource - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, - NodeTypeEnum.Resource); - if (lockResult != 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)); - throw new ByResponseFormatComponentException(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)) { - validateDerivedFromNotEmpty(null, newResource, null); - validateDerivedFromNotEmpty(null, currentResource, null); - } else { - newResource.setDerivedFrom(null); - } - - Either dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, - user, currentResource, false, true); - if (dataModelResponse.isRight()) { - log.debug("failed to update resource metadata!!!"); - throw new ByResponseFormatComponentException(dataModelResponse.right().value()); + private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { + String iconUpdated = updateInfoResource.getIcon(); + String iconCurrent = currentResource.getIcon(); + if (!iconCurrent.equals(iconUpdated)) { + if (!hasBeenCertified) { + componentIconValidator.validateAndCorrectField(null, updateInfoResource, null); + } else { + log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); } + } + } - log.debug("Resource metadata updated successfully!!!"); - return dataModelResponse.left() - .value(); + private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) { + String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber(); + String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber(); + if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) { + validateResourceVendorModelNumber(null, updateInfoResource, null); + } + } - } catch (ComponentException | StorageException e) { - rollback(inTransaction, newResource, null, null); - throw e; - } finally { - if (!inTransaction) { - janusGraphDao.commit(); - } - if (needToUnlock) { - graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); - } - } - } - - private Either updateResourceMetadata(String resourceIdToUpdate, Resource newResource, - User user, Resource currentResource, boolean shouldLock, boolean inTransaction) { - updateVfModuleGroupsNames(currentResource, newResource); - validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false); - // 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(), 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 (isNotEmpty(newResource.getGroups())) { - for (GroupDefinition group : newResource.getGroups()) { - if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) { - groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition() - .getMetadataDataDefinition() - .getUniqueId(), user, newResource.getComponentType(), 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()); - } - - private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) { - if (currentResource.getGroups() != null && !currentResource.getName() - .equals(newResource.getName())) { - List updatedGroups = currentResource.getGroups() - .stream() - .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName())) - .collect(toList()); - newResource.setGroups(updatedGroups); - } - } - - private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) { - GroupDefinition updatedGroup = new GroupDefinition(currGroup); - if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType() - .equals(DEFAULT_GROUP_VF_MODULE)) { - String prefix = updatedGroup.getName() - .substring(0, replacePattern.length()); - String newGroupName = updatedGroup.getName() - .replaceFirst(prefix, with); - updatedGroup.setName(newGroupName); - } - return updatedGroup; - } - - /** - * validateResourceFieldsBeforeCreate - * - * @param user - * - modifier data (userId) - */ - private void validateResourceFieldsBeforeCreate(User user, Resource resource, - AuditingActionEnum actionEnum, boolean inTransaction) { - componentValidator.validate(user, resource, actionEnum); - // validate category - log.debug("validate category"); - validateCategory(user, resource, actionEnum, inTransaction); - // validate vendor name & release & model number - log.debug("validate vendor name"); - validateVendorName(user, resource, actionEnum); - log.debug("validate vendor release"); - validateVendorReleaseName(user, resource, actionEnum); - log.debug("validate resource vendor model number"); - validateResourceVendorModelNumber(user, resource, actionEnum); - // validate cost - log.debug("validate cost"); - validateCost(resource); - // validate licenseType - log.debug("validate licenseType"); - validateLicenseType(user, resource, actionEnum); - // validate template (derived from) - log.debug("validate derived from"); - if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) { - resource.setDerivedFrom(null); - } - validateDerivedFromExist(user, resource, actionEnum); - // warn about non-updatable fields - checkComponentFieldsForOverrideAttempt(resource); - String currentCreatorFullName = resource.getCreatorFullName(); - if (currentCreatorFullName != null) { - log.debug("Resource Creator fullname is automatically set and cannot be updated"); - } - - String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); - if (currentLastUpdaterFullName != null) { - log.debug("Resource LastUpdater fullname is automatically set and cannot be updated"); - } - - Long currentLastUpdateDate = resource.getLastUpdateDate(); - if (currentLastUpdateDate != null) { - log.debug("Resource last update date is automatically set and cannot be updated"); - } - - Boolean currentAbstract = resource.isAbstract(); - if (currentAbstract != null) { - log.debug("Resource abstract is automatically set and cannot be updated"); - } - } - - /** - * validateResourceFieldsBeforeUpdate - * - * @param currentResource - * - Resource object to validate - * @param isNested - */ - private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, - boolean inTransaction, boolean isNested) { - validateFields(currentResource, updateInfoResource, inTransaction, isNested); - warnNonEditableFields(currentResource, updateInfoResource); - } - - private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) { - String currentResourceVersion = currentResource.getVersion(); - String updatedResourceVersion = updateInfoResource.getVersion(); - - if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) { - log.debug("Resource version is automatically set and cannot be updated"); - } - - String currentCreatorUserId = currentResource.getCreatorUserId(); - String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); - - if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { - log.debug("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.debug("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.debug("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.debug("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.debug("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.debug("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.debug("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.debug("Resource abstract is automatically set and cannot be updated"); - } - - Boolean currentHighestVersion = currentResource.isHighestVersion(); - Boolean updatedHighestVersion = updateInfoResource.isHighestVersion(); - - if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) { - log.debug("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.debug("Resource UUID is automatically set and cannot be updated"); - } - - log.debug("Resource Type cannot be updated"); - String currentInvariantUuid = currentResource.getInvariantUUID(); - String updatedInvariantUuid = updateInfoResource.getInvariantUUID(); - - if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { - log.debug("Resource invariant UUID is automatically set and cannot be updated"); - updateInfoResource.setInvariantUUID(currentInvariantUuid); - } - } - - private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, - boolean isNested) { - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); - log.debug("validate resource name before update"); - validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested); - log.debug("validate description before update"); - componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null); - log.debug("validate icon before update"); - validateIcon(currentResource, updateInfoResource, hasBeenCertified); - log.debug("validate tags before update"); - componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null); - log.debug("validate vendor name before update"); - validateVendorName(null, updateInfoResource, null); - log.debug("validate resource vendor model number before update"); - validateResourceVendorModelNumber(currentResource, updateInfoResource); - log.debug("validate vendor release before update"); - validateVendorReleaseName(null, updateInfoResource, null); - log.debug("validate contact info before update"); - componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null); - log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); - validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified); - log.debug("validate category before update"); - validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction); - } - - 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() == ResourceTypeEnum.CVFC - && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent)); - } - - private String addCvfcSuffixToResourceName(String resourceName) { - return resourceName + "Cvfc"; - } - - private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, - boolean isNested) { - String resourceNameUpdated = updateInfoResource.getName(); - if (!isResourceNameEquals(currentResource, updateInfoResource)) { - if (isNested || !hasBeenCertified) { - componentNameValidator.validateAndCorrectField(null, updateInfoResource, null); - validateResourceNameUniqueness(updateInfoResource); - 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); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); - } - } - } - - private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - String iconUpdated = updateInfoResource.getIcon(); - String iconCurrent = currentResource.getIcon(); - if (!iconCurrent.equals(iconUpdated)) { - if (!hasBeenCertified) { - componentIconValidator.validateAndCorrectField(null, updateInfoResource, null); - } else { - log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); - } - } - } - - private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) { - String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber(); - String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber(); - if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) { - validateResourceVendorModelNumber(null, updateInfoResource, null); - } - } - - private Either validateCategory(Resource currentResource, Resource updateInfoResource, - boolean hasBeenCertified, boolean inTransaction) { - validateCategory(null, updateInfoResource, null, inTransaction); - 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) { - validateDerivedFromExist(null, updateInfoResource, null); - } 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) { - validateDerivedFromExist(null, updateInfoResource, null); - } 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 void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { - if (resource.getDerivedFrom() == null || resource.getDerivedFrom() - .isEmpty()) { - return; - } - 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); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus)); - } 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); - throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - } - - // 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 void 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); - - throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - } - - private void validateResourceNameUniqueness(Resource resource) { - - Either resourceOperationResponse = toscaOperationFacade - .validateComponentNameExists(resource.getName(), resource.getResourceType(), - resource.getComponentType()); - if (resourceOperationResponse.isLeft() && resourceOperationResponse.left() - .value()) { - log.debug("resource with name: {}, already exists", resource.getName()); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, - ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - } else if (resourceOperationResponse.isRight()) { - log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); - throw new StorageException(resourceOperationResponse.right() - .value()); - } - } - - private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - - List categories = resource.getCategories(); - if (CollectionUtils.isEmpty(categories)) { - log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - } - if (categories.size() > 1) { - log.debug("Must be only one category for resource"); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, - ComponentTypeEnum.RESOURCE.getValue()); - } - CategoryDefinition category = categories.get(0); - List subcategories = category.getSubcategories(); - if (CollectionUtils.isEmpty(subcategories)) { - log.debug("Missinig subcategory for resource"); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - } - if (subcategories.size() > 1) { - log.debug("Must be only one sub category for resource"); - throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); - } - - SubCategoryDefinition subcategory = subcategories.get(0); - - if (!ValidationUtils.validateStringNotEmpty(category.getName())) { - log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - } - if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { - log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - } - - validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction); - } - - private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, - Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - ResponseFormat responseFormat; - 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 retrieve resource categories from JanusGraph"); - responseFormat = componentsUtils.getResponseFormat(categories.right() - .value()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(categories.right() - .value()); - } - List categoryList = categories.left() - .value(); - Optional foundCategory = categoryList.stream() - .filter(cat -> cat.getName() - .equals(category.getName())) - .findFirst(); - if (!foundCategory.isPresent()) { - log.debug("Category {} is not part of resource category group. Resource category valid values are {}", - category, categoryList); - failOnInvalidCategory(user, resource, actionEnum); - } - Optional foundSubcategory = foundCategory.get() - .getSubcategories() - .stream() - .filter(subcat -> subcat.getName() - .equals(subcategory.getName())) - .findFirst(); - if (!foundSubcategory.isPresent()) { - log.debug( - "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", - subcategory, foundCategory.get() - .getSubcategories()); - failOnInvalidCategory(user, resource, actionEnum); - } - } - } - - private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) { - ResponseFormat responseFormat; - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - public void 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); - throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE); - } - - validateVendorReleaseName(vendorRelease, user, resource, actionEnum); - } - - public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, - AuditingActionEnum actionEnum) { - 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); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, - "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - if (!ValidationUtils.validateVendorRelease(vendorRelease)) { - log.info("vendor release is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); - componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + private Either validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, + boolean inTransaction) { + validateCategory(null, updateInfoResource, null, inTransaction); + 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) { + validateDerivedFromExist(null, updateInfoResource, null); + } 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) { + validateDerivedFromExist(null, updateInfoResource, null); + } 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 void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { + if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) { + return; + } + 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); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus)); + } 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); + throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + } + + // 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 void 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); + throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + } + + private void validateResourceNameUniqueness(Resource resource) { + Either resourceOperationResponse = toscaOperationFacade + .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); + if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) { + log.debug("resource with name: {}, already exists", resource.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), + resource.getName()); + } else if (resourceOperationResponse.isRight()) { + log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); + throw new StorageException(resourceOperationResponse.right().value()); + } + } + + private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { + List categories = resource.getCategories(); + if (CollectionUtils.isEmpty(categories)) { + log.debug(CATEGORY_IS_EMPTY); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + if (categories.size() > 1) { + log.debug("Must be only one category for resource"); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue()); + } + CategoryDefinition category = categories.get(0); + List subcategories = category.getSubcategories(); + if (CollectionUtils.isEmpty(subcategories)) { + log.debug("Missinig subcategory for resource"); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + } + if (subcategories.size() > 1) { + log.debug("Must be only one sub category for resource"); + throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); + } + SubCategoryDefinition subcategory = subcategories.get(0); + if (!ValidationUtils.validateStringNotEmpty(category.getName())) { + log.debug(CATEGORY_IS_EMPTY); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { + log.debug(CATEGORY_IS_EMPTY); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction); + } + + private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource, + AuditingActionEnum actionEnum, boolean inTransaction) { + ResponseFormat responseFormat; + 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 retrieve resource categories from JanusGraph"); + responseFormat = componentsUtils.getResponseFormat(categories.right().value()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(categories.right().value()); + } + List categoryList = categories.left().value(); + Optional foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName())).findFirst(); + if (!foundCategory.isPresent()) { + log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList); + failOnInvalidCategory(user, resource, actionEnum); + } + Optional foundSubcategory = foundCategory.get().getSubcategories().stream() + .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst(); + if (!foundSubcategory.isPresent()) { + log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, + foundCategory.get().getSubcategories()); + failOnInvalidCategory(user, resource, actionEnum); + } + } + } + + private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) { + ResponseFormat responseFormat; + responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + public void 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); + throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE); + } + validateVendorReleaseName(vendorRelease, user, resource, actionEnum); + } + + public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) { + 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); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + if (!ValidationUtils.validateVendorRelease(vendorRelease)) { + log.info("vendor release is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease); } } } - private void validateVendorName(User user, Resource resource, - AuditingActionEnum actionEnum) { + private void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) { String vendorName = resource.getVendorName(); if (!ValidationUtils.validateStringNotEmpty(vendorName)) { log.info("vendor name is missing."); @@ -5472,18 +4594,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { validateVendorName(vendorName, user, resource, actionEnum); } - private void validateVendorName(String vendorName, User user, Resource resource, - AuditingActionEnum actionEnum) { + private void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) { 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); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, - "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); } - if (!ValidationUtils.validateVendorName(vendorName)) { log.info("vendor name is not valid."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME); @@ -5498,26 +4617,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { if (StringUtils.isNotEmpty(resourceVendorModelNumber)) { 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); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, + "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, - "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); + "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); } // 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); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); } } } - private void validateCost(Resource resource) { String cost = resource.getCost(); if (cost != null) { @@ -5528,13 +4645,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - private void validateLicenseType(User user, Resource resource, - AuditingActionEnum actionEnum) { + private void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate licenseType"); String licenseType = resource.getLicenseType(); if (licenseType != null) { - List licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration() - .getLicenseTypes(); + List licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes(); if (!licenseTypes.contains(licenseType)) { log.debug("License type {} isn't configured", licenseType); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -5547,509 +4662,437 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - private Either processUpdateOfDerivedFrom(Resource currentResource, - Resource updatedResource, String userId, boolean inTransaction) { - 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 - Either deleteArtifactByInterface = - artifactsBusinessLogic.deleteArtifactByInterface(resourceId, userId, uniqueId, true); - if (deleteArtifactByInterface.isRight()) { - log.debug("Couldn't remove artifact definition with id {}", uniqueId); - if (!inTransaction) { - janusGraphDao.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() != StorageOperationStatus.OK) { - log.debug("Failed to remove all properties of resource"); - if (!inTransaction) { + private Either processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, + boolean inTransaction) { + 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 + Either deleteArtifactByInterface = artifactsBusinessLogic + .deleteArtifactByInterface(resourceId, userId, uniqueId, true); + if (deleteArtifactByInterface.isRight()) { + log.debug("Couldn't remove artifact definition with id {}", uniqueId); + if (!inTransaction) { + janusGraphDao.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() != StorageOperationStatus.OK) { + log.debug("Failed to remove all properties of resource"); + if (!inTransaction) { janusGraphDao.rollback(); - } - return Either.right(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right() - .value()))); - } - - } else { - log.debug("Derived from wasn't changed during update"); - } - - if (inTransaction) { - return Either.left(true); - } + } + return Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value()))); + } + } else { + log.debug("Derived from wasn't changed during update"); + } + if (inTransaction) { + return Either.left(true); + } janusGraphDao.commit(); - return Either.left(true); - - } - - public ICapabilityTypeOperation getCapabilityTypeOperation() { - return capabilityTypeOperation; - } - - @Autowired - public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { - this.capabilityTypeOperation = capabilityTypeOperation; - } - - public Boolean validatePropertiesDefaultValues(Resource resource) { - log.debug("validate resource properties default values"); - List properties = resource.getProperties(); - if (properties != null) { - iterateOverProperties(properties); - } - return true; - } - - public void iterateOverProperties(List properties) { - String type = null; - String innerType = null; - for (PropertyDefinition property : properties) { - if (!propertyOperation.isPropertyTypeValid(property)) { - log.info("Invalid type for property {}", property); - throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE, - property.getType(), property.getName()); - } - - Map allDataTypes = getAllDataTypes(applicationDataTypeCache); - type = property.getType(); - - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes); - if (responseFormat != null) { - break; - } - } - validateDefaultPropertyValue(property, allDataTypes, type, innerType); - } - } - - private void validateDefaultPropertyValue(PropertyDefinition property, - Map allDataTypes, String type, String innerType) { - if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) { - log.info("Invalid default value for property {}", property); - ResponseFormat responseFormat; - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, - property.getName(), type, innerType, property.getDefaultValue()); - } - throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE, - property.getName(), type, property.getDefaultValue()); - } - } - - private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, - Map allDataTypes) { - ResponseFormat responseFormat = null; - ImmutablePair propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, - allDataTypes); - innerType = propertyInnerTypeValid.getLeft(); - if (!propertyInnerTypeValid.getRight() - .booleanValue()) { - log.info("Invalid inner type for property {}", property); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, - property.getName()); - } - return responseFormat; - } - - @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; - } - - public Either getLatestResourceFromCsarUuid(String csarUuid, User user) { - // validate user - if (user != null) { - validateUserExists(user); - } - // 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, String userId) { - return null; - } - - private Map> getValidComponentInstanceCapabilities(String resourceId, - Map> defaultCapabilities, - Map> uploadedCapabilities) { - - Map> validCapabilitiesMap = new HashMap<>(); - uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, - defaultCapabilities, validCapabilitiesMap)); - return validCapabilitiesMap; - } - - private void addValidComponentInstanceCapabilities(String key, List capabilities, String resourceId, - Map> defaultCapabilities, - Map> validCapabilitiesMap) { - String capabilityType = capabilities.get(0) - .getType(); - if (defaultCapabilities.containsKey(capabilityType)) { - CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType); - validateCapabilityProperties(capabilities, resourceId, defaultCapability); - List validCapabilityList = new ArrayList<>(); - validCapabilityList.add(defaultCapability); - validCapabilitiesMap.put(key, validCapabilityList); - } else { - throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType); - } - } - - private void validateCapabilityProperties(List capabilities, String resourceId, - CapabilityDefinition defaultCapability) { - if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.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()); - throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId); - } else if (isNotEmpty(capabilities.get(0) - .getProperties())) { - validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0)); - } - } - - private CapabilityDefinition getCapability(String resourceId, - Map> defaultCapabilities, String capabilityType) { - CapabilityDefinition defaultCapability; - if (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()); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId); - } - defaultCapability = getFullComponentRes.left() - .value() - .getCapabilities() - .get(capabilityType) - .get(0); - } - return defaultCapability; - } - - private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, - UploadCapInfo uploadedCapability) { - List validProperties = new ArrayList<>(); - Map defaultProperties = defaultCapability.getProperties() - .stream() - .collect(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) - && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) { - throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, 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); - } - - private boolean propertTypeEqualsTo(Map defaultProperties, String propertyName, - String propertyType) { - return propertyType != null && !defaultProperties.get(propertyName) - .getType() - .equals(propertyType); - } - - 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 (foundArtifact.getArtifactType().equals(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_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, - currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), - foundArtifact.getArtifactType()); - AuditingActionEnum auditingAction = artifactsBusinessLogic - .detectAuditingType(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, - currArtifact.getArtifactType(), - currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), - currArtifact.getIsFromCsar())); - } else { - artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, - 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 occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); - } - return nodeTypeArtifactsToHandleRes; - } - - ImmutablePair buildNestedToscaResourceName(final String nodeResourceType, - final String vfResourceName, - final 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; - } - String nameWithouNamespacePrefix; - try { - final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName); - log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, " - + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName, - nodeTypeFullName, actualType, vfResourceName); - final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix); - - if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) { - nameWithouNamespacePrefix = nodeTypeFullName; - } else { - nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length()); - } - final String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String actualName; - if (nodeResourceType.equalsIgnoreCase(findTypes[0])){ - actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length()); - } else { - actualName = "." + nameWithouNamespacePrefix; - } - - if (actualName.startsWith(Constants.ABSTRACT)) { - toscaResourceName.append(nodeResourceType.toLowerCase()).append('.') - .append(ValidationUtils.convertToSystemName(actualVfName)); - } else { - toscaResourceName.append(actualType.toLowerCase()).append('.') - .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); - } - final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); - final String[] actualNames = actualName.split("\\."); - if (actualNames.length < 3) { - return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), - previousToscaResourceName.append(actualName).toString()); - } - return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), - previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1) - .toLowerCase()).toString()); - } catch (final Exception e) { - log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e); - throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName); - } - } - - /** - * Extracts a Node Type Name prefix from the given Node Type Name. - * - * @param fullName Node Type Name - * @return Node Type Name Prefix - */ - private String getNodeTypeNamePrefix(final String fullName) { - String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX; - final List definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList(); - log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList); - final Optional validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList); - if (validNameSpace.isPresent()) { - tempPrefix = validNameSpace.get(); - } - log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix); - return tempPrefix; - } - - @Override - public Either getUiComponentDataTransferByComponentId(String resourceId, - List dataParamsToReturn) { - - ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn); - Either resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToReturn); - - if (resourceResultEither.isRight()) { - if (resourceResultEither.right().value() == 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(); - if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) { - ListUtils.emptyIfNull(resource.getInputs()) - .forEach(input -> input.setConstraints(setInputConstraint(input))); - } - - 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); - } - } + return Either.left(true); + } + + public ICapabilityTypeOperation getCapabilityTypeOperation() { + return capabilityTypeOperation; + } + + @Autowired + public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { + this.capabilityTypeOperation = capabilityTypeOperation; + } + + public Boolean validatePropertiesDefaultValues(Resource resource) { + log.debug("validate resource properties default values"); + List properties = resource.getProperties(); + if (properties != null) { + iterateOverProperties(properties); + } + return true; + } + + public void iterateOverProperties(List properties) { + String type = null; + String innerType = null; + for (PropertyDefinition property : properties) { + if (!propertyOperation.isPropertyTypeValid(property)) { + log.info("Invalid type for property {}", property); + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); + } + Map allDataTypes = getAllDataTypes(applicationDataTypeCache); + type = property.getType(); + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes); + if (responseFormat != null) { + break; + } + } + validateDefaultPropertyValue(property, allDataTypes, type, innerType); + } + } + + private void validateDefaultPropertyValue(PropertyDefinition property, Map allDataTypes, String type, + String innerType) { + if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) { + log.info("Invalid default value for property {}", property); + ResponseFormat responseFormat; + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, + property.getDefaultValue()); + } + throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); + } + } + + private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, + Map allDataTypes) { + ResponseFormat responseFormat = null; + ImmutablePair propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes); + innerType = propertyInnerTypeValid.getLeft(); + if (!propertyInnerTypeValid.getRight().booleanValue()) { + log.info("Invalid inner type for property {}", property); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); + } + return responseFormat; + } + + @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; + } + + public Either getLatestResourceFromCsarUuid(String csarUuid, User user) { + // validate user + if (user != null) { + validateUserExists(user); + } + // 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, String userId) { + return null; + } + + private Map> getValidComponentInstanceCapabilities(String resourceId, + Map> defaultCapabilities, + Map> uploadedCapabilities) { + Map> validCapabilitiesMap = new HashMap<>(); + uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap)); + return validCapabilitiesMap; + } + + private void addValidComponentInstanceCapabilities(String key, List capabilities, String resourceId, + Map> defaultCapabilities, + Map> validCapabilitiesMap) { + String capabilityType = capabilities.get(0).getType(); + if (defaultCapabilities.containsKey(capabilityType)) { + CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType); + validateCapabilityProperties(capabilities, resourceId, defaultCapability); + List validCapabilityList = new ArrayList<>(); + validCapabilityList.add(defaultCapability); + validCapabilitiesMap.put(key, validCapabilityList); + } else { + throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType); + } + } + + private void validateCapabilityProperties(List capabilities, String resourceId, CapabilityDefinition defaultCapability) { + if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.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()); + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId); + } else if (isNotEmpty(capabilities.get(0).getProperties())) { + validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0)); + } + } + + private CapabilityDefinition getCapability(String resourceId, Map> defaultCapabilities, + String capabilityType) { + CapabilityDefinition defaultCapability; + if (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()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId); + } + defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0); + } + return defaultCapability; + } + + private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, + UploadCapInfo uploadedCapability) { + List validProperties = new ArrayList<>(); + Map defaultProperties = defaultCapability.getProperties().stream() + .collect(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) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) { + throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, 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); + } + + private boolean propertTypeEqualsTo(Map defaultProperties, String propertyName, String propertyType) { + return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType); + } + + 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 (foundArtifact.getArtifactType().equals(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_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), + currNewArtifact.getArtifactType(), foundArtifact.getArtifactType()); + AuditingActionEnum auditingAction = artifactsBusinessLogic + .detectAuditingType(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, currArtifact.getArtifactType(), + currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); + } else { + artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, 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 occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + } + return nodeTypeArtifactsToHandleRes; + } + + ImmutablePair buildNestedToscaResourceName(final String nodeResourceType, final String vfResourceName, + final 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; + } + String nameWithouNamespacePrefix; + try { + final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName); + log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, " + + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName, nodeTypeFullName, actualType, + vfResourceName); + final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix); + if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) { + nameWithouNamespacePrefix = nodeTypeFullName; + } else { + nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length()); + } + final String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String actualName; + if (nodeResourceType.equalsIgnoreCase(findTypes[0])) { + actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length()); + } else { + actualName = "." + nameWithouNamespacePrefix; + } + if (actualName.startsWith(Constants.ABSTRACT)) { + toscaResourceName.append(nodeResourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)); + } else { + toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.') + .append(Constants.ABSTRACT); + } + final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); + final String[] actualNames = actualName.split("\\."); + if (actualNames.length < 3) { + return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), + previousToscaResourceName.append(actualName).toString()); + } + return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), + previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1).toLowerCase()).toString()); + } catch (final Exception e) { + log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e); + throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName); + } + } + + /** + * Extracts a Node Type Name prefix from the given Node Type Name. + * + * @param fullName Node Type Name + * @return Node Type Name Prefix + */ + private String getNodeTypeNamePrefix(final String fullName) { + String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX; + final List definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList(); + log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList); + final Optional validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList); + if (validNameSpace.isPresent()) { + tempPrefix = validNameSpace.get(); + } + log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix); + return tempPrefix; + } + + @Override + public Either getUiComponentDataTransferByComponentId(String resourceId, + List dataParamsToReturn) { + ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn); + Either resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToReturn); + if (resourceResultEither.isRight()) { + if (resourceResultEither.right().value() == 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(); + if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) { + ListUtils.emptyIfNull(resource.getInputs()).forEach(input -> input.setConstraints(setInputConstraint(input))); + } + 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); + } + } } 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 8ea1c2a28f..787bc3e2de 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 @@ -19,12 +19,10 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation.createDataType; import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation.createDataTypeDefinitionWithName; -import static org.openecomp.sdc.be.utils.TypeUtils.setField; import fj.data.Either; import java.util.ArrayList; @@ -102,33 +100,18 @@ import org.yaml.snakeyaml.Yaml; @Component("resourceImportManager") public class ResourceImportManager { - private static final Logger log = Logger.getLogger(ResourceImportManager.class); - static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern.compile("[\\w\\-\\_\\d\\:]+"); + private static final Logger log = Logger.getLogger(ResourceImportManager.class); private final InterfaceDefinitionHandler interfaceDefinitionHandler; - + private final ComponentsUtils componentsUtils; + private final CapabilityTypeOperation capabilityTypeOperation; private ServletContext servletContext; - private AuditingManager auditingManager; private ResourceBusinessLogic resourceBusinessLogic; - - public ServiceBusinessLogic getServiceBusinessLogic() { - return serviceBusinessLogic; - } - - public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) { - this.serviceBusinessLogic = serviceBusinessLogic; - } - @Autowired private ServiceBusinessLogic serviceBusinessLogic; - private IGraphLockOperation graphLockOperation; private ToscaOperationFacade toscaOperationFacade; - - private final ComponentsUtils componentsUtils; - private final CapabilityTypeOperation capabilityTypeOperation; - private ResponseFormatManager responseFormatManager; @Autowired @@ -139,88 +122,74 @@ public class ResourceImportManager { this.interfaceDefinitionHandler = interfaceDefinitionHandler; } + public ServiceBusinessLogic getServiceBusinessLogic() { + return serviceBusinessLogic; + } + + public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) { + this.serviceBusinessLogic = serviceBusinessLogic; + } + @Autowired public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { this.toscaOperationFacade = toscaOperationFacade; } - public ImmutablePair importNormativeResource(String resourceYml, - UploadResourceInfo resourceMetaData, - User creator, boolean createNewVersion, - boolean needLock) { - + public ImmutablePair 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); + Function validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, + null, null, false, null, null, false); } - public ImmutablePair importNormativeResourceFromCsar(String resourceYml, - UploadResourceInfo resourceMetaData, - User creator, boolean createNewVersion, - boolean needLock) { - + public ImmutablePair 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); + Function validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, + null, null, false, null, null, false); } - public ImmutablePair importCertifiedResource(String resourceYml, - UploadResourceInfo resourceMetaData, - User creator, + public ImmutablePair importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function validationFunction, - LifecycleChangeInfoWithAction lifecycleChangeInfo, - boolean isInTransaction, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, - boolean forceCertificationAllowed, - CsarInfo csarInfo, String nodeName, + 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); - populateResourceFromYaml(resourceYml, resource); - validationFunction.apply(resource); if (!createNewVersion) { - Either latestByName = toscaOperationFacade - .getLatestByName(resource.getName()); + Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); if (latestByName.isLeft()) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, - resource.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource.getName()); } } else { - final Either component = toscaOperationFacade.getComponentByNameAndVendorRelease(resource.getComponentType(), resource.getName(), resource.getVendorRelease(), JsonParseFlagEnum.ParseAll); + final Either component = toscaOperationFacade + .getComponentByNameAndVendorRelease(resource.getComponentType(), resource.getName(), resource.getVendorRelease(), + JsonParseFlagEnum.ParseAll); if (component.isLeft()) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, - resource.getName()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, resource.getName()); } } resource = resourceBusinessLogic - .createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, - isNested).left; + .createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested).left; Resource changeStateResponse; - if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) { - Either, ResponseFormat> handleNodeTypeArtifactsRes = - resourceBusinessLogic - .handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, - creator, isInTransaction, false); + Either, ResponseFormat> handleNodeTypeArtifactsRes = resourceBusinessLogic + .handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false); if (handleNodeTypeArtifactsRes.isRight()) { //TODO: should be used more correct action throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); @@ -228,10 +197,8 @@ public class ResourceImportManager { } latestCertifiedResourceId = getLatestCertifiedResourceId(resource); changeStateResponse = resourceBusinessLogic - .propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, - forceCertificationAllowed); - responsePair = new ImmutablePair<>(changeStateResponse, response.left() - .value().right); + .propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed); + responsePair = new ImmutablePair<>(changeStateResponse, response.left().value().right); } catch (RuntimeException e) { handleImportResourceException(resourceMetaData, creator, true, e); } finally { @@ -240,7 +207,6 @@ public class ResourceImportManager { graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource); } } - return responsePair; } @@ -279,45 +245,34 @@ public class ResourceImportManager { } } - public ImmutablePair importUserDefinedResource(String resourceYml, - UploadResourceInfo resourceMetaData, - User creator, boolean isInTransaction) { - + public ImmutablePair importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, + boolean isInTransaction) { Resource resource = new Resource(); ImmutablePair responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); - try { setMetaDataFromJson(resourceMetaData, resource); - populateResourceFromYaml(resourceYml, resource); - // currently import VF isn't supported. In future will be supported + // import VF only with CSAR file!! if (ResourceTypeEnum.VF == resource.getResourceType()) { log.debug("Now import VF isn't supported. It will be supported in future with CSAR file only"); throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); } - resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); Boolean validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); - - responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, - false, isInTransaction, true, null, null, false); - + responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false); } catch (RuntimeException e) { handleImportResourceException(resourceMetaData, creator, false, e); } return responsePair; - } private void populateResourceFromYaml(String resourceYml, Resource resource) { - @SuppressWarnings("unchecked") - Object ymlObj = new Yaml().load(resourceYml); + @SuppressWarnings("unchecked") Object ymlObj = new Yaml().load(resourceYml); if (ymlObj instanceof Map) { Map toscaJsonAll = (Map) ymlObj; Map toscaJson = toscaJsonAll; - // Checks if exist and builds the node_types map if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType() != ResourceTypeEnum.CVFC) { @@ -326,8 +281,8 @@ public class ResourceImportManager { toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName())); } final List foundElements = new ArrayList<>(); - final Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements(toscaJsonAll, - ToscaTagNamesEnum.DATA_TYPES.getElementName(), ToscaElementTypeEnum.MAP, foundElements); + final Either, ResultStatusEnum> toscaElements = ImportUtils + .findToscaElements(toscaJsonAll, ToscaTagNamesEnum.DATA_TYPES.getElementName(), ToscaElementTypeEnum.MAP, foundElements); if (toscaElements.isLeft()) { final Map toscaAttributes = (Map) foundElements.get(0); if (MapUtils.isNotEmpty(toscaAttributes)) { @@ -347,7 +302,6 @@ public class ResourceImportManager { } else { throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } - } private void setToscaResourceName(Map toscaJson, Resource resource) { @@ -366,16 +320,13 @@ public class ResourceImportManager { Map jsonInterfaces = toscaInterfaces.left().value(); Map moduleInterfaces = new HashMap<>(); for (final Entry interfaceNameValue : jsonInterfaces.entrySet()) { - final Either eitherInterface = - createModuleInterface(interfaceNameValue.getValue()); + final Either eitherInterface = createModuleInterface(interfaceNameValue.getValue()); if (eitherInterface.isRight()) { - log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), - resource.getName()); + log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName()); } else { final InterfaceDefinition interfaceDefinition = eitherInterface.left().value(); moduleInterfaces.put(interfaceNameValue.getKey(), interfaceDefinition); } - } if (!moduleInterfaces.isEmpty()) { resource.setInterfaces(moduleInterfaces); @@ -390,13 +341,11 @@ public class ResourceImportManager { interfaceDefinition.setType((String) interfaceJson); return Either.left(interfaceDefinition); } - if (interfaceJson instanceof Map) { final Map interfaceJsonMap = (Map) interfaceJson; final InterfaceDefinition interfaceDefinition = interfaceDefinitionHandler.create(interfaceJsonMap); return Either.left(interfaceDefinition); } - return Either.right(ResultStatusEnum.GENERAL_ERROR); } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface"); @@ -415,6 +364,7 @@ public class ResourceImportManager { // Checking for name duplication Set reqNames = new HashSet<>(); // Getting flattened list of capabilities of parent node - cap name + // to cap type Map reqName2TypeMap = getReqName2Type(parentResource); for (Object jsonRequirementObj : jsonRequirements) { @@ -423,15 +373,11 @@ public class ResourceImportManager { 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); - throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, - "requirement", reqNameLowerCase); + log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase); } reqNames.add(reqNameLowerCase); - RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper - .get(requirementName)); + RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName)); requirementDef.setName(requirementName); if (moduleRequirements.containsKey(requirementDef.getCapability())) { moduleRequirements.get(requirementDef.getCapability()).add(requirementDef); @@ -440,51 +386,39 @@ public class ResourceImportManager { list.add(requirementDef); moduleRequirements.put(requirementDef.getCapability(), list); } - // Validating against req/cap of "derived from" node - Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef - .getCapability(), requirementDef.getName()); + Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName()); if (!validateVsParentCap) { String parentResourceName = parentResource != null ? parentResource.getName() : ""; - log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), - parentResourceName); - throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, - "requirement", requirementDef - .getName() - .toLowerCase(), parentResourceName); + log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResourceName); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", + requirementDef.getName().toLowerCase(), parentResourceName); } } if (moduleRequirements.size() > 0) { resource.setRequirements(moduleRequirements); } - } } private RequirementDefinition createRequirementFromImportFile(Object requirementJson) { RequirementDefinition requirement = new RequirementDefinition(); - if (requirementJson instanceof String) { String requirementJsonString = (String) requirementJson; requirement.setCapability(requirementJsonString); } else if (requirementJson instanceof Map) { Map requirementJsonMap = (Map) requirementJson; if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())) { - requirement.setCapability( - (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())); + requirement.setCapability((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())); } - if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())) { requirement.setNode((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())); } - if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())) { - requirement.setRelationship( - (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())); + requirement.setRelationship((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())); } if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List occurrencesList = (List) requirementJsonMap - .get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); + List occurrencesList = (List) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); validateOccurrences(occurrencesList); requirement.setMinOccurrences(occurrencesList.get(0).toString()); requirement.setMaxOccurrences(occurrencesList.get(1).toString()); @@ -498,8 +432,7 @@ public class ResourceImportManager { private void setProperties(Map toscaJson, Resource resource) { Map reducedToscaJson = new HashMap<>(toscaJson); ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); - Either, ResultStatusEnum> properties = ImportUtils - .getProperties(reducedToscaJson); + Either, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); if (properties.isLeft()) { List propertiesList = new ArrayList<>(); Map value = properties.left().value(); @@ -507,11 +440,9 @@ public class ResourceImportManager { 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()); - throw new ByActionStatusComponentException(componentsUtils - .convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, - JsonPresentationFields.PROPERTY)); + log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); + throw new ByActionStatusComponentException( + componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY)); } PropertyDefinition propertyDefinition = entry.getValue(); propertyDefinition.setName(name); @@ -520,27 +451,22 @@ public class ResourceImportManager { } resource.setProperties(propertiesList); } else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) { - throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(properties - .right() - .value(), JsonPresentationFields.PROPERTY)); + throw new ByActionStatusComponentException( + componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY)); } } private void setAttributes(final Map originalToscaJsonMap, final Resource resource) { final Map toscaJsonMap = new HashMap<>(originalToscaJsonMap); ImportUtils.removeElementFromJsonMap(toscaJsonMap, "capabilities"); - final Either, ResultStatusEnum> getAttributeEither = ImportUtils - .getAttributes(toscaJsonMap); - + final Either, ResultStatusEnum> getAttributeEither = ImportUtils.getAttributes(toscaJsonMap); if (getAttributeEither.isRight()) { final ResultStatusEnum resultStatus = getAttributeEither.right().value(); if (resultStatus == ResultStatusEnum.ELEMENT_NOT_FOUND) { return; } - throw new ByActionStatusComponentException( - componentsUtils.convertFromResultStatusEnum(resultStatus, JsonPresentationFields.ATTRIBUTES)); + throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(resultStatus, JsonPresentationFields.ATTRIBUTES)); } - final List attributeDefinitionList = new ArrayList<>(); final Map attributeMap = getAttributeEither.left().value(); if (MapUtils.isEmpty(attributeMap)) { @@ -549,11 +475,9 @@ public class ResourceImportManager { for (final Entry entry : attributeMap.entrySet()) { final String name = entry.getKey(); if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) { - log.debug("Detected attribute with invalid name '{}' during resource '{}' import. ", - name, resource.getName()); - throw new ByActionStatusComponentException(componentsUtils - .convertFromResultStatusEnum(ResultStatusEnum.INVALID_ATTRIBUTE_NAME, - JsonPresentationFields.ATTRIBUTES)); + log.debug("Detected attribute with invalid name '{}' during resource '{}' import. ", name, resource.getName()); + throw new ByActionStatusComponentException( + componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_ATTRIBUTE_NAME, JsonPresentationFields.ATTRIBUTES)); } final AttributeDefinition attributeDefinition = entry.getValue(); attributeDefinition.setName(name); @@ -570,9 +494,7 @@ public class ResourceImportManager { 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); - + Either latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom); if (latestByToscaResourceName.isRight()) { StorageOperationStatus operationStatus = latestByToscaResourceName.right().value(); if (operationStatus == StorageOperationStatus.NOT_FOUND) { @@ -580,8 +502,7 @@ public class ResourceImportManager { } log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus); ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); - BeEcompErrorManager.getInstance() - .logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); + BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); throw new ByActionStatusComponentException(convertFromStorageResponse, derivedFrom); } derivedFromResource = latestByToscaResourceName.left().value(); @@ -599,24 +520,19 @@ public class ResourceImportManager { Iterator> capabilitiesNameValue = jsonCapabilities.entrySet().iterator(); Set capNames = new HashSet<>(); // Getting flattened list of capabilities of parent node - cap name + // to cap type Map capName2TypeMap = getCapName2Type(parentResource); 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); - throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", - capNameLowerCase); + log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase); } capNames.add(capNameLowerCase); - - CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue - .getValue()); + CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue.getValue()); capabilityDef.setName(capabilityNameValue.getKey()); if (moduleCapabilities.containsKey(capabilityDef.getType())) { moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef); @@ -625,22 +541,18 @@ public class ResourceImportManager { list.add(capabilityDef); moduleCapabilities.put(capabilityDef.getType(), list); } - // Validating against req/cap of "derived from" node - Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef - .getType(), capabilityDef.getName()); - + Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName()); if (!validateVsParentCap) { // Here parentResource is for sure not null, so it's + // null-safe + // Check added to avoid sonar warning String parentResourceName = parentResource != null ? parentResource.getName() : ""; - log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), - parentResourceName); - throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, - "capability", capabilityDef - .getName() - .toLowerCase(), parentResourceName); + log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResourceName); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", + capabilityDef.getName().toLowerCase(), parentResourceName); } } if (moduleCapabilities.size() > 0) { @@ -659,12 +571,11 @@ public class ResourceImportManager { 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); + 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); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } capName2type.put(nameLowerCase, capDefinition.getType()); @@ -685,12 +596,11 @@ public class ResourceImportManager { 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); + 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); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } reqName2type.put(nameLowerCase, reqDefinition.getCapability()); @@ -701,26 +611,21 @@ public class ResourceImportManager { return reqName2type; } - private Boolean validateCapNameVsDerived(Map parentCapName2Type, String childCapabilityType, - String reqCapName) { + private Boolean 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); + log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, + childCapabilityType); return 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"); - throw new ByActionStatusComponentException( - componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom - .right() - .value())); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value())); } return capabilityTypeDerivedFrom.left().value(); } @@ -728,9 +633,7 @@ public class ResourceImportManager { } private CapabilityDefinition createCapabilityFromImportFile(Object capabilityJson) { - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - if (capabilityJson instanceof String) { String capabilityJsonString = (String) capabilityJson; capabilityDefinition.setType(capabilityJsonString); @@ -738,66 +641,48 @@ public class ResourceImportManager { Map capabilityJsonMap = (Map) capabilityJson; // Type if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) { - capabilityDefinition - .setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())); + capabilityDefinition.setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())); } // ValidSourceTypes if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { - capabilityDefinition.setValidSourceTypes( - (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES - .getElementName())); + capabilityDefinition + .setValidSourceTypes((List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())); } // ValidSourceTypes if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - capabilityDefinition.setDescription( - (String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())); + capabilityDefinition.setDescription((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())); } if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List occurrencesList = (List) capabilityJsonMap - .get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); + List occurrencesList = (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); validateOccurrences(occurrencesList); capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString()); capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString()); } if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName())) { - - Either, ResultStatusEnum> propertiesRes = ImportUtils - .getProperties(capabilityJsonMap); + Either, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap); if (propertiesRes.isRight()) { throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND); } 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()); + 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)) { throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML); } return capabilityDefinition; } - private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, - RuntimeException e) { + private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) { ResponseFormat responseFormat; ComponentException newException; if (e instanceof ComponentException) { ComponentException componentException = (ComponentException) e; responseFormat = componentException.getResponseFormat(); if (responseFormat == null) { - responseFormat = getResponseFormatManager() - .getResponseFormat(componentException.getActionStatus(), componentException.getParams()); + responseFormat = getResponseFormatManager().getResponseFormat(componentException.getActionStatus(), componentException.getParams()); } newException = componentException; } else { @@ -811,8 +696,7 @@ public class ResourceImportManager { throw newException; } - private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, - boolean isNormative) { + private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) { String version, lifeCycleState; if (isNormative) { version = TypeUtils.getFirstCertifiedVersionVersion(); @@ -820,44 +704,27 @@ public class ResourceImportManager { } else { version = ""; lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); - } - 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(), - new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()), - ResourceVersionInfo.newBuilder() - .state(lifeCycleState) - .version(version) - .build(), - ResourceVersionInfo.newBuilder() - .state("") - .version("") - .build(), - "", user, ""); + CommonAuditData.newBuilder().status(errorResponseWrapper.getStatus()).description(message).requestId(ThreadLocalsHolder.getUuid()) + .build(), new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()), + ResourceVersionInfo.newBuilder().state(lifeCycleState).version(version).build(), + ResourceVersionInfo.newBuilder().state("").version("").build(), "", user, ""); getAuditingManager().auditEvent(factory); - } private void setMetaDataFromJson(final UploadResourceInfo resourceMetaData, final Resource resource) { this.populateResourceMetadata(resourceMetaData, resource); resource.setCreatorUserId(resourceMetaData.getContactId()); - final String payloadData = resourceMetaData.getPayloadData(); if (payloadData != null) { resource.setToscaVersion(getToscaVersion(payloadData)); } - final List categories = resourceMetaData.getCategories(); calculateResourceIsAbstract(resource, categories); } @@ -869,8 +736,8 @@ public class ResourceImportManager { private String getToscaVersion(final String payloadData) { final Map mappedToscaTemplate = decodePayload(payloadData); - final Either findFirstToscaStringElement = - ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); + final Either findFirstToscaStringElement = ImportUtils + .findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); if (findFirstToscaStringElement.isLeft()) { return findFirstToscaStringElement.left().value(); } else { @@ -882,8 +749,7 @@ public class ResourceImportManager { 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)) { + 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); @@ -907,16 +773,13 @@ public class ResourceImportManager { resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); resource.setVendorName(ImportUtils.Constants.VENDOR_NAME); resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE); - } private void validateOccurrences(List occurrensesList) { - if (!ValidationUtils.validateListNotEmpty(occurrensesList)) { log.debug("Occurrenses list empty"); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } - if (occurrensesList.size() < 2) { log.debug("Occurrenses list size not 2"); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); @@ -935,7 +798,6 @@ public class ResourceImportManager { log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } - if (maxObj instanceof String) { if (!"UNBOUNDED".equals(maxObj)) { log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); @@ -948,10 +810,8 @@ public class ResourceImportManager { log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } - if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) { - log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, - maxOccurrences); + log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } } @@ -980,10 +840,19 @@ public class ResourceImportManager { return servletContext; } + public void setServletContext(ServletContext servletContext) { + this.servletContext = servletContext; + } + public AuditingManager getAuditingManager() { return auditingManager; } + @Autowired + public void setAuditingManager(AuditingManager auditingManager) { + this.auditingManager = auditingManager; + } + public ResponseFormatManager getResponseFormatManager() { return responseFormatManager; } @@ -1010,31 +879,19 @@ public class ResourceImportManager { this.graphLockOperation = graphLockOperation; } - public void setServletContext(ServletContext servletContext) { - this.servletContext = servletContext; - } - - @Autowired - public void setAuditingManager(AuditingManager auditingManager) { - this.auditingManager = auditingManager; - } - private List extractDataTypeFromJson(final ResourceBusinessLogic resourceBusinessLogic, final Map foundElements) { final List dataTypeDefinitionList = new ArrayList<>(); if (MapUtils.isNotEmpty(foundElements)) { - final Either, JanusGraphOperationStatus> dataTypeCacheAll = - resourceBusinessLogic.dataTypeCache.getAll(); + final Either, JanusGraphOperationStatus> dataTypeCacheAll = resourceBusinessLogic.dataTypeCache.getAll(); if (dataTypeCacheAll.isLeft()) { for (final Entry attributeNameValue : foundElements.entrySet()) { final Object value = attributeNameValue.getValue(); if (value instanceof Map) { - final DataTypeDefinition dataTypeDefinition = - createDataTypeDefinitionWithName(attributeNameValue); - final DataTypeDefinition dataTypeDefinitionParent = - dataTypeCacheAll.left().value().get(dataTypeDefinition.getDerivedFromName()); + final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue); + final DataTypeDefinition dataTypeDefinitionParent = dataTypeCacheAll.left().value() + .get(dataTypeDefinition.getDerivedFromName()); dataTypeDefinition.setDerivedFrom(dataTypeDefinitionParent); - dataTypeDefinitionList.add(dataTypeDefinition); } else { dataTypeDefinitionList.add(createDataType(String.valueOf(value))); 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 2cb03fe2ed..875bcb214c 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -33,9 +32,9 @@ import org.openecomp.sdc.exception.ServiceException; public class ResponseFormatManager { + private static final Logger log = Logger.getLogger(ResponseFormatManager.class); private volatile static ResponseFormatManager instance; private static ConfigurationManager configurationManager; - private static final Logger log = Logger.getLogger(ResponseFormatManager.class); public static ResponseFormatManager getInstance() { if (instance == null) { 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 ad1f818da6..a87fdb6ca7 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 @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.impl; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; @@ -165,10 +164,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.context.WebApplicationContext; - @org.springframework.stereotype.Component("serviceBusinessLogic") public class ServiceBusinessLogic extends ComponentBusinessLogic { + static final String IS_VALID = "isValid"; private static final String THE_SERVICE_WITH_SYSTEM_NAME_LOCKED = "The service with system name {} locked. "; private static final String FAILED_TO_LOCK_SERVICE_RESPONSE_IS = "Failed to lock service {}. Response is {}. "; private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response"; @@ -176,71 +175,40 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private static final String INITIAL_VERSION = "0.1"; private static final String STATUS_SUCCESS_200 = "200"; private static final String STATUS_DEPLOYED = "DEPLOYED"; - static final String IS_VALID = "isValid"; private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; - - private ForwardingPathOperation forwardingPathOperation; - private AuditCassandraDao auditCassandraDao; - private final IDistributionEngine distributionEngine; private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; private final ServiceDistributionValidation serviceDistributionValidation; private final ForwardingPathValidator forwardingPathValidator; private final UiComponentDataConverter uiComponentDataConverter; - + private ForwardingPathOperation forwardingPathOperation; + private AuditCassandraDao auditCassandraDao; private ServiceTypeValidator serviceTypeValidator; private List serviceCreationPluginList; - - @Autowired - public void setServiceTypeValidator(ServiceTypeValidator serviceTypeValidator) { - this.serviceTypeValidator = serviceTypeValidator; - } - - private ServiceFunctionValidator serviceFunctionValidator; - - @Autowired - public void setServiceFunctionValidator(ServiceFunctionValidator serviceFunctionValidator) { - this.serviceFunctionValidator = serviceFunctionValidator; - } - @Autowired private ServiceRoleValidator serviceRoleValidator; - @Autowired private ServiceInstantiationTypeValidator serviceInstantiationTypeValidator; - @Autowired private ServiceCategoryValidator serviceCategoryValidator; - @Autowired private ServiceValidator serviceValidator; - @Autowired - public ServiceBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsBusinessLogic artifactsBusinessLogic, + public ServiceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsBusinessLogic artifactsBusinessLogic, IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator, - UiComponentDataConverter uiComponentDataConverter, - ArtifactsOperations artifactToscaOperation, - ComponentContactIdValidator componentContactIdValidator, - ComponentNameValidator componentNameValidator, - ComponentTagsValidator componentTagsValidator, - ComponentValidator componentValidator, - ComponentIconValidator componentIconValidator, - ComponentProjectCodeValidator componentProjectCodeValidator, + UiComponentDataConverter uiComponentDataConverter, ArtifactsOperations artifactToscaOperation, + ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator, ComponentDescriptionValidator componentDescriptionValidator) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, - interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, - componentNameValidator, componentTagsValidator, componentValidator, - componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation, + interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator, + componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator); this.distributionEngine = distributionEngine; this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; this.serviceDistributionValidation = serviceDistributionValidation; @@ -248,12 +216,20 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { this.uiComponentDataConverter = uiComponentDataConverter; } + @Autowired + public void setServiceTypeValidator(ServiceTypeValidator serviceTypeValidator) { + this.serviceTypeValidator = serviceTypeValidator; + } + + @Autowired + public void setServiceFunctionValidator(ServiceFunctionValidator serviceFunctionValidator) { + this.serviceFunctionValidator = serviceFunctionValidator; + } public Either>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) { validateUserExists(userId); Either>, ActionStatus> result; try { - // Certified Version if (componentVersion.endsWith(".0")) { Either, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID); @@ -271,229 +247,154 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { 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()); } - } - public Either, ResponseFormat> addServiceConsumptionData(String serviceId, - String serviceInstanceId, - String operationId, - List serviceConsumptionDataList, - String userId) { + public Either, ResponseFormat> addServiceConsumptionData(String serviceId, String serviceInstanceId, String operationId, + List serviceConsumptionDataList, String userId) { List operationList = new ArrayList<>(); - - Either serviceEither = - toscaOperationFacade.getToscaElement(serviceId); - if(serviceEither.isRight()) { - return Either.right(componentsUtils.getResponseFormat - (serviceEither.right().value())); + Either serviceEither = toscaOperationFacade.getToscaElement(serviceId); + if (serviceEither.isRight()) { + return Either.right(componentsUtils.getResponseFormat(serviceEither.right().value())); } - Service service = serviceEither.left().value(); - - - StorageOperationStatus storageOperationStatus = - graphLockOperation.lockComponent(service.getUniqueId(), NodeTypeEnum.Service); + StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(service.getUniqueId(), NodeTypeEnum.Service); if (storageOperationStatus != StorageOperationStatus.OK) { return Either.right(componentsUtils.getResponseFormat(storageOperationStatus)); } - try { for (ServiceConsumptionData serviceConsumptionData : serviceConsumptionDataList) { - Either operationEither = - addPropertyServiceConsumption(serviceId, serviceInstanceId, operationId, - userId, serviceConsumptionData); - + Either operationEither = addPropertyServiceConsumption(serviceId, serviceInstanceId, operationId, userId, + serviceConsumptionData); if (operationEither.isRight()) { return Either.right(operationEither.right().value()); } - operationList.add(operationEither.left().value()); } - janusGraphDao.commit(); return Either.left(operationList); } catch (Exception e) { janusGraphDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); - } } - public Either addPropertyServiceConsumption(String serviceId, - String serviceInstanceId, - String operationId, - String userId, - ServiceConsumptionData serviceConsumptionData) { + public Either addPropertyServiceConsumption(String serviceId, String serviceInstanceId, String operationId, + String userId, ServiceConsumptionData serviceConsumptionData) { validateUserExists(userId); - - Either serviceEither = - toscaOperationFacade.getToscaElement(serviceId); - if(serviceEither.isRight()) { - return Either.right(componentsUtils.getResponseFormat(serviceEither.right - ().value())); + Either serviceEither = toscaOperationFacade.getToscaElement(serviceId); + if (serviceEither.isRight()) { + return Either.right(componentsUtils.getResponseFormat(serviceEither.right().value())); } - Service parentService = serviceEither.left().value(); - List componentInstances = parentService.getComponentInstances(); - if(CollectionUtils.isEmpty(componentInstances)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); + if (CollectionUtils.isEmpty(componentInstances)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); } - - Optional serviceInstanceCandidate = - componentInstances.stream().filter(instance -> instance.getUniqueId().equals - (serviceInstanceId)).findAny(); - - if(!serviceInstanceCandidate.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); + Optional serviceInstanceCandidate = componentInstances.stream() + .filter(instance -> instance.getUniqueId().equals(serviceInstanceId)).findAny(); + if (!serviceInstanceCandidate.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); } - - Map> componentInstancesInterfaces = - parentService.getComponentInstancesInterfaces(); - if(MapUtils.isEmpty(componentInstancesInterfaces)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); + Map> componentInstancesInterfaces = parentService.getComponentInstancesInterfaces(); + if (MapUtils.isEmpty(componentInstancesInterfaces)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); } - List interfaces = new ArrayList<>(); - for(ComponentInstanceInterface componentInstanceInterface : - componentInstancesInterfaces.get(serviceInstanceId)) { + for (ComponentInstanceInterface componentInstanceInterface : componentInstancesInterfaces.get(serviceInstanceId)) { interfaces.add(componentInstanceInterface); } - ComponentInstance serviceInstance = serviceInstanceCandidate.get(); - Optional interfaceCandidate = InterfaceOperationUtils - .getInterfaceDefinitionFromOperationId(interfaces, operationId); - - if(!interfaceCandidate.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); + Optional interfaceCandidate = InterfaceOperationUtils.getInterfaceDefinitionFromOperationId(interfaces, operationId); + if (!interfaceCandidate.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); } - InterfaceDefinition interfaceDefinition = interfaceCandidate.get(); Map operations = interfaceDefinition.getOperationsMap(); - if(MapUtils.isEmpty(operations)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); + if (MapUtils.isEmpty(operations)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); } - Operation operation = operations.get(operationId); Either operationEither = Either.left(operation); - ListDataDefinition inputs = operation.getInputs(); - Optional inputCandidate = - getOperationInputByInputId(serviceConsumptionData, inputs); - - if(!inputCandidate.isPresent()) { + Optional inputCandidate = getOperationInputByInputId(serviceConsumptionData, inputs); + if (!inputCandidate.isPresent()) { return Either.right(new ResponseFormat(HttpStatus.NOT_FOUND.value())); } - OperationInputDefinition operationInputDefinition = inputCandidate.get(); // add data to operation - - if(Objects.nonNull(serviceConsumptionData.getValue())) { - operationEither = - handleConsumptionValue(parentService, serviceInstanceId, serviceConsumptionData, operation, - operationInputDefinition); + if (Objects.nonNull(serviceConsumptionData.getValue())) { + operationEither = handleConsumptionValue(parentService, serviceInstanceId, serviceConsumptionData, operation, operationInputDefinition); } - - if(operationEither.isRight()) { + if (operationEither.isRight()) { return Either.right(operationEither.right().value()); } - Operation updatedOperation = operationEither.left().value(); operations.remove(operationId); operations.put(operationId, updatedOperation); interfaceDefinition.setOperationsMap(operations); - parentService.getComponentInstances().remove(serviceInstance); - if(CollectionUtils.isEmpty(parentService.getComponentInstances())) { + if (CollectionUtils.isEmpty(parentService.getComponentInstances())) { parentService.setComponentInstances(new ArrayList<>()); } - Map instanceInterfaces = - MapUtils.isEmpty(serviceInstance.getInterfaces())? new HashMap<>() : serviceInstance.getInterfaces(); + MapUtils.isEmpty(serviceInstance.getInterfaces()) ? new HashMap<>() : serviceInstance.getInterfaces(); instanceInterfaces.remove(interfaceDefinition.getUniqueId()); instanceInterfaces.put(interfaceDefinition.getUniqueId(), interfaceDefinition); serviceInstance.setInterfaces(instanceInterfaces); - removeComponentInstanceInterfaceByInterfaceId(interfaceDefinition.getUniqueId(), componentInstancesInterfaces.get(serviceInstanceId)); - componentInstancesInterfaces.get(serviceInstanceId).add(new ComponentInstanceInterface(interfaceDefinition.getUniqueId(), interfaceDefinition)); - + componentInstancesInterfaces.get(serviceInstanceId) + .add(new ComponentInstanceInterface(interfaceDefinition.getUniqueId(), interfaceDefinition)); parentService.getComponentInstances().add(serviceInstance); - StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceInterfaces(parentService, serviceInstanceId); - - if(status != StorageOperationStatus.OK) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); + if (status != StorageOperationStatus.OK) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId)); } - return Either.left(operation); } - private void removeComponentInstanceInterfaceByInterfaceId(String interfaceIdToRemove, - List instanceInterfaces) { - if(CollectionUtils.isEmpty(instanceInterfaces)) { + private void removeComponentInstanceInterfaceByInterfaceId(String interfaceIdToRemove, List instanceInterfaces) { + if (CollectionUtils.isEmpty(instanceInterfaces)) { return; } - - Optional interfaceToRemove = - instanceInterfaces.stream().filter(instInterface -> instInterface.getUniqueId().equals - (interfaceIdToRemove)).findAny(); - - if(interfaceToRemove.isPresent()) { + Optional interfaceToRemove = instanceInterfaces.stream() + .filter(instInterface -> instInterface.getUniqueId().equals(interfaceIdToRemove)).findAny(); + if (interfaceToRemove.isPresent()) { instanceInterfaces.remove(interfaceToRemove.get()); } - } - private Either handleConsumptionValue(Service containerService, - String serviceInstanceId, - ServiceConsumptionData serviceConsumptionData, - Operation operation, - OperationInputDefinition - operationInputDefinition) { + private Either handleConsumptionValue(Service containerService, String serviceInstanceId, + ServiceConsumptionData serviceConsumptionData, Operation operation, + OperationInputDefinition operationInputDefinition) { String source = serviceConsumptionData.getSource(); String consumptionValue = serviceConsumptionData.getValue(); String type = serviceConsumptionData.getType(); - String operationIdentifier = consumptionValue.contains(".") - ? consumptionValue.substring(0, consumptionValue.lastIndexOf('.')) - : consumptionValue; - + String operationIdentifier = + consumptionValue.contains(".") ? consumptionValue.substring(0, consumptionValue.lastIndexOf('.')) : consumptionValue; ServiceConsumptionSource sourceValue = ServiceConsumptionSource.getSourceValue(source); - - if(STATIC.equals(sourceValue)) { + if (STATIC.equals(sourceValue)) { // Validate constraint on input value - Either constraintValidationResult = - validateOperationInputConstraint(operationInputDefinition, consumptionValue, type); - + Either constraintValidationResult = validateOperationInputConstraint(operationInputDefinition, consumptionValue, + type); if (constraintValidationResult.isRight()) { return Either.right(constraintValidationResult.right().value()); } - return handleConsumptionStaticValue(consumptionValue, type, operation, - operationInputDefinition); + return handleConsumptionStaticValue(consumptionValue, type, operation, operationInputDefinition); } - if (Objects.isNull(sourceValue)) { List propertyDefinitions; Map> capabilities = null; String componentName; List outputs = null; if (source.equals(containerService.getUniqueId())) { - Either serviceToTakePropEither = - toscaOperationFacade.getToscaElement(source); + Either serviceToTakePropEither = toscaOperationFacade.getToscaElement(source); if (serviceToTakePropEither.isRight()) { return Either.right(componentsUtils.getResponseFormat(serviceToTakePropEither.right().value())); } @@ -502,13 +403,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { sourceValue = SERVICE_INPUT; propertyDefinitions = service.getProperties(); componentName = service.getName(); - outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier, - service.getInterfaces()).getListToscaDataDefinition(); + outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier, service.getInterfaces()) + .getListToscaDataDefinition(); } else { Optional getComponentInstance = containerService.getComponentInstanceById(source); - if(!getComponentInstance.isPresent()){ - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, source)); + if (!getComponentInstance.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, source)); } ComponentInstance componentInstance = getComponentInstance.get(); operationInputDefinition.setSource(componentInstance.getUniqueId()); @@ -516,185 +416,143 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { capabilities = componentInstance.getCapabilities(); componentName = source.equals(serviceInstanceId) ? SELF : componentInstance.getName(); if (MapUtils.isNotEmpty(componentInstance.getInterfaces())) { - Map componentInstanceInterfaces = - componentInstance.getInterfaces().entrySet().stream() - .collect(Collectors.toMap((Map.Entry::getKey), - (interfaceEntry -> (InterfaceDataDefinition) interfaceEntry.getValue()))); - outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier, - componentInstanceInterfaces).getListToscaDataDefinition(); + Map componentInstanceInterfaces = componentInstance.getInterfaces().entrySet().stream() + .collect(Collectors.toMap((Map.Entry::getKey), (interfaceEntry -> (InterfaceDataDefinition) interfaceEntry.getValue()))); + outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier, componentInstanceInterfaces) + .getListToscaDataDefinition(); } } - - if(sourceValue == ServiceConsumptionSource.SERVICE_INPUT) { + if (sourceValue == ServiceConsumptionSource.SERVICE_INPUT) { //The operation input in service consumption has been mapped to an input in the parent service - return handleConsumptionInputValue(consumptionValue, containerService, operation, - operationInputDefinition); + return handleConsumptionInputValue(consumptionValue, containerService, operation, operationInputDefinition); } - return handleConsumptionPropertyValue(operation, operationInputDefinition, - serviceConsumptionData, propertyDefinitions, capabilities, outputs, componentName); + return handleConsumptionPropertyValue(operation, operationInputDefinition, serviceConsumptionData, propertyDefinitions, capabilities, + outputs, componentName); } - operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.SOURCE, source); operationInputDefinition.setSource(source); - return Either.left(operation); } private Optional getOperationInputByInputId(ServiceConsumptionData serviceConsumptionData, ListDataDefinition inputs) { - - if(CollectionUtils.isEmpty(inputs.getListToscaDataDefinition())) { + if (CollectionUtils.isEmpty(inputs.getListToscaDataDefinition())) { return Optional.empty(); } - - return inputs.getListToscaDataDefinition().stream().filter(operationInput -> operationInput.getInputId().equals - (serviceConsumptionData.getInputId())) - .findAny(); + return inputs.getListToscaDataDefinition().stream() + .filter(operationInput -> operationInput.getInputId().equals(serviceConsumptionData.getInputId())).findAny(); } - private Either handleConsumptionPropertyValue( - Operation operation, OperationInputDefinition operationInputDefinition, - ServiceConsumptionData serviceConsumptionData, List properties,Map> capabilities, - List outputs, String componentName) { - + private Either handleConsumptionPropertyValue(Operation operation, OperationInputDefinition operationInputDefinition, + ServiceConsumptionData serviceConsumptionData, + List properties, + Map> capabilities, + List outputs, String componentName) { if (CollectionUtils.isEmpty(properties) && CollectionUtils.isEmpty(outputs)) { return Either.left(operation); } String consumptionValue = serviceConsumptionData.getValue(); - - if (CollectionUtils.isNotEmpty(outputs) - && isOperationInputMappedToOtherOperationOutput(getOperationOutputName(consumptionValue), outputs)) { - return handleConsumptionInputMappedToOperationOutput(operation, operationInputDefinition, outputs, - consumptionValue, componentName); + if (CollectionUtils.isNotEmpty(outputs) && isOperationInputMappedToOtherOperationOutput(getOperationOutputName(consumptionValue), outputs)) { + return handleConsumptionInputMappedToOperationOutput(operation, operationInputDefinition, outputs, consumptionValue, componentName); } - if (CollectionUtils.isNotEmpty(properties) && PropertiesUtils.isNodeProperty(consumptionValue, properties)) { - return handleConsumptionInputMappedToProperty(operation, operationInputDefinition, serviceConsumptionData, - properties, componentName); + return handleConsumptionInputMappedToProperty(operation, operationInputDefinition, serviceConsumptionData, properties, componentName); } - if (MapUtils.isNotEmpty(capabilities)) { - return handleConsumptionInputMappedToCapabilityProperty(operation, operationInputDefinition, - serviceConsumptionData, capabilities, componentName); + return handleConsumptionInputMappedToCapabilityProperty(operation, operationInputDefinition, serviceConsumptionData, capabilities, + componentName); } - return Either.left(operation); } private Either handleConsumptionInputMappedToProperty(Operation operation, - OperationInputDefinition operationInputDefinition, ServiceConsumptionData serviceConsumptionData, + OperationInputDefinition operationInputDefinition, + ServiceConsumptionData serviceConsumptionData, List properties, String componentName) { - Optional servicePropertyCandidate = - properties.stream().filter(property -> property.getName() - .equals(serviceConsumptionData.getValue())).findAny(); - + Optional servicePropertyCandidate = properties.stream() + .filter(property -> property.getName().equals(serviceConsumptionData.getValue())).findAny(); if (servicePropertyCandidate.isPresent()) { - boolean isInputTypeSimilarToOperation = - isAssignedValueFromValidType(operationInputDefinition.getType(), - servicePropertyCandidate.get()); - + boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), servicePropertyCandidate.get()); if (!isInputTypeSimilarToOperation) { - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType())); } - - addPropertyToInputValue(componentName, operation, operationInputDefinition, - servicePropertyCandidate.get()); + addPropertyToInputValue(componentName, operation, operationInputDefinition, servicePropertyCandidate.get()); } return Either.left(operation); } private Either handleConsumptionInputMappedToOperationOutput(Operation operation, - OperationInputDefinition operationInputDefinition, List outputs, + OperationInputDefinition operationInputDefinition, + List outputs, String consumptionValue, String componentName) { String outputName = getOperationOutputName(consumptionValue); - Optional servicePropertyOutputCandidate = outputs.stream() - .filter(output -> output.getName().equals(outputName)).findAny(); + Optional servicePropertyOutputCandidate = outputs.stream().filter(output -> output.getName().equals(outputName)) + .findAny(); if (servicePropertyOutputCandidate.isPresent()) { - boolean isInputTypeSimilarToOperation = - isAssignedValueFromValidType(operationInputDefinition.getType(), - servicePropertyOutputCandidate.get()); + boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), + servicePropertyOutputCandidate.get()); if (!isInputTypeSimilarToOperation) { - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType())); } addOutputToInputValue(componentName, consumptionValue, operation, operationInputDefinition); } return Either.left(operation); } - private void addPropertyToInputValue(String componentName, Operation operation, - OperationInputDefinition operationInputDefinition, + private void addPropertyToInputValue(String componentName, Operation operation, OperationInputDefinition operationInputDefinition, PropertyDefinition serviceProperty) { Map> getProperty = new HashMap<>(); List getPropertyValues = new ArrayList<>(); getPropertyValues.add(componentName); getPropertyValues.add(serviceProperty.getName()); getProperty.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), getPropertyValues); - operationInputDefinition.setSourceProperty(serviceProperty.getUniqueId()); operation.getInputs().delete(operationInputDefinition); - operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY, - getPropertyValues); + operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY, getPropertyValues); operationInputDefinition.setValue((new Gson()).toJson(getProperty)); operation.getInputs().add(operationInputDefinition); } - private void addOutputToInputValue(String componentName, String consumptionValue, - Operation operation, OperationInputDefinition operationInputDefinition) { - Map> getOperationOutput = - InterfaceOperationUtils.createMappedOutputDefaultValue(componentName, consumptionValue); + private void addOutputToInputValue(String componentName, String consumptionValue, Operation operation, + OperationInputDefinition operationInputDefinition) { + Map> getOperationOutput = InterfaceOperationUtils.createMappedOutputDefaultValue(componentName, consumptionValue); operation.getInputs().delete(operationInputDefinition); - operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_OPERATION_OUTPUT, - getOperationOutput); + operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_OPERATION_OUTPUT, getOperationOutput); operationInputDefinition.setValue((new Gson()).toJson(getOperationOutput)); operation.getInputs().add(operationInputDefinition); } - public Either handleConsumptionStaticValue(String value, String type, - Operation operation, - OperationInputDefinition - operationInputDefinition) { - boolean isInputTypeSimilarToOperation = - isAssignedValueFromValidType(type, value); - - if(!isInputTypeSimilarToOperation) { - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_CONSUMPTION_TYPE, type)); + public Either handleConsumptionStaticValue(String value, String type, Operation operation, + OperationInputDefinition operationInputDefinition) { + boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(type, value); + if (!isInputTypeSimilarToOperation) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, type)); + } + //Validate Constraint and Value + Either constraintValidationResponse = validateOperationInputConstraint(operationInputDefinition, value, type); + if (constraintValidationResponse.isRight()) { + return Either.right(constraintValidationResponse.right().value()); } - - //Validate Constraint and Value - Either constraintValidationResponse = - validateOperationInputConstraint(operationInputDefinition, value, type); - if(constraintValidationResponse.isRight()) { - return Either.right(constraintValidationResponse.right().value()); - } - addStaticValueToInputOperation(value, operation, operationInputDefinition); - return Either.left(operation); } - private Either validateOperationInputConstraint( - OperationInputDefinition operationInputDefinition, String value, String type) { - ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty(); - propertyDefinition.setType(operationInputDefinition.getParentPropertyType()); - - InputDefinition inputDefinition = new InputDefinition(); - inputDefinition.setDefaultValue(value); - inputDefinition.setInputPath(operationInputDefinition.getSubPropertyInputPath()); - inputDefinition.setType(type); - if (Objects.nonNull(operationInputDefinition.getParentPropertyType())) { - inputDefinition.setProperties(Collections.singletonList(propertyDefinition)); - } - - return PropertyValueConstraintValidationUtil.getInstance() - .validatePropertyConstraints(Collections.singletonList(inputDefinition), applicationDataTypeCache); - } + private Either validateOperationInputConstraint(OperationInputDefinition operationInputDefinition, String value, + String type) { + ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty(); + propertyDefinition.setType(operationInputDefinition.getParentPropertyType()); + InputDefinition inputDefinition = new InputDefinition(); + inputDefinition.setDefaultValue(value); + inputDefinition.setInputPath(operationInputDefinition.getSubPropertyInputPath()); + inputDefinition.setType(type); + if (Objects.nonNull(operationInputDefinition.getParentPropertyType())) { + inputDefinition.setProperties(Collections.singletonList(propertyDefinition)); + } + return PropertyValueConstraintValidationUtil.getInstance() + .validatePropertyConstraints(Collections.singletonList(inputDefinition), applicationDataTypeCache); + } - private void addStaticValueToInputOperation(String value, Operation operation, - OperationInputDefinition operationInputDefinition) { + private void addStaticValueToInputOperation(String value, Operation operation, OperationInputDefinition operationInputDefinition) { operation.getInputs().delete(operationInputDefinition); operationInputDefinition.setSource(STATIC.getSource()); operationInputDefinition.setSourceProperty(null); @@ -702,31 +560,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { operation.getInputs().add(operationInputDefinition); } - private Either handleConsumptionInputValue(String inputId, - Service service, - Operation operation, - OperationInputDefinition - operationInputDefinition) { + private Either handleConsumptionInputValue(String inputId, Service service, Operation operation, + OperationInputDefinition operationInputDefinition) { List serviceInputs = service.getInputs(); - Optional inputForValue = - serviceInputs.stream().filter(input -> input.getUniqueId().contains(inputId)).findAny(); - - if(inputForValue.isPresent()) { - boolean isInputTypeSimilarToOperation = - isAssignedValueFromValidType(operationInputDefinition.getType(), inputForValue.get()); - - if(!isInputTypeSimilarToOperation) { - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType())); + Optional inputForValue = serviceInputs.stream().filter(input -> input.getUniqueId().contains(inputId)).findAny(); + if (inputForValue.isPresent()) { + boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), inputForValue.get()); + if (!isInputTypeSimilarToOperation) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType())); } addGetInputValueToOperationInput(operation, operationInputDefinition, inputForValue.get()); } - return Either.left(operation); } - private void addGetInputValueToOperationInput(Operation operation, - OperationInputDefinition operationInputDefinition, + private void addGetInputValueToOperationInput(Operation operation, OperationInputDefinition operationInputDefinition, InputDefinition inputForValue) { operation.getInputs().delete(operationInputDefinition); Map getInputMap = new HashMap<>(); @@ -739,38 +587,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) { // First Query - Either, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion); - + 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); + Either, ActionStatus> eitherCurrVerAudit = auditCassandraDao + .getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion); if (eitherCurrVerAudit.isRight()) { return Either.right(eitherCurrVerAudit.right().value()); } - - Either, ActionStatus> eitherArchiveRestoreList = getArchiveRestoreEventList(componentUUID); if (eitherArchiveRestoreList.isRight()) { return Either.right(eitherArchiveRestoreList.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); joinedNonDuplicatedList.addAll(getAuditingFieldsList(eitherArchiveRestoreList.left().value())); - - return Either.left(joinedNonDuplicatedList); } @@ -780,17 +621,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (eitherArchiveAudit.isRight()) { return Either.right(eitherArchiveAudit.right().value()); } - // Restore Query Either, ActionStatus> eitherRestoreAudit = auditCassandraDao.getRestoreAuditByServiceInstanceId(componentUUID); if (eitherRestoreAudit.isRight()) { return Either.right(eitherRestoreAudit.right().value()); } - List archiveAudit = new ArrayList<>(); archiveAudit.addAll(eitherArchiveAudit.left().value()); archiveAudit.addAll(eitherRestoreAudit.left().value()); - return Either.left(archiveAudit); } @@ -805,7 +643,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } private List> getAuditingFieldsList(List prevVerAuditList) { - List> prevVerAudit = new ArrayList<>(); for (AuditingGenericEvent auditEvent : prevVerAuditList) { auditEvent.fillFields(); @@ -817,17 +654,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { /** * createService * - * @param service - * - Service - * @param user - * - modifier data (userId) + * @param service - Service + * @param user - modifier data (userId) * @return Either */ public Either createService(Service service, User user) { - // get user details user = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false); - log.debug("User returned from validation: "+ user.toString()); + log.debug("User returned from validation: " + user.toString()); // validate user role validateUserRole(user, service, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null); service.setCreatorUserId(user.getUserId()); @@ -844,11 +678,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (createServiceResponse.isRight()) { return createServiceResponse; } - return createServiceByDao(service, user) - .left() - .bind(c -> updateCatalog(c, ChangeTypeEnum.LIFECYCLE) - .left() - .map (r -> (Service) r)); + return createServiceByDao(service, user).left().bind(c -> updateCatalog(c, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Service) r)); } private void checkFieldsForOverideAttampt(Service service) { @@ -860,17 +690,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private Either createServiceByDao(final Service service, final 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, AuditingActionEnum.CREATE_RESOURCE, - ComponentTypeEnum.SERVICE); + componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); return Either.right(responseFormat); } - log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult); - try { createMandatoryArtifactsData(service, user); createServiceApiArtifactsData(service, user); @@ -879,20 +705,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { generatePropertiesFromGenericType(service, genericType); generateAndAddInputsFromGenericTypeProperties(service, genericType); beforeCreate(service); - Either dataModelResponse = toscaOperationFacade.createToscaComponent(service); if (dataModelResponse.isLeft()) { log.debug("Service '{}' created successfully", service.getName()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, - ComponentTypeEnum.SERVICE); + componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); ASDCKpiApi.countCreatedServicesKPI(); return Either.left(dataModelResponse.left().value()); } - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, + ComponentTypeEnum.SERVICE); log.debug(AUDIT_BEFORE_SENDING_RESPONSE); - componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, - ComponentTypeEnum.SERVICE); + componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); return Either.right(responseFormat); } finally { graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service); @@ -903,36 +728,29 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (CollectionUtils.isEmpty(serviceCreationPluginList)) { return; } - serviceCreationPluginList.stream() - .sorted(Comparator.comparingInt(ServiceCreationPlugin::getOrder)) - .forEach(serviceCreationPlugin -> { - try { - serviceCreationPlugin.beforeCreate(service); - } catch (final Exception e) { - log.error("An error has occurred while running the serviceCreationPlugin '{}'", - serviceCreationPlugin.getClass(), e); - } - }); + serviceCreationPluginList.stream().sorted(Comparator.comparingInt(ServiceCreationPlugin::getOrder)).forEach(serviceCreationPlugin -> { + try { + serviceCreationPlugin.beforeCreate(service); + } catch (final Exception e) { + log.error("An error has occurred while running the serviceCreationPlugin '{}'", serviceCreationPlugin.getClass(), e); + } + }); } private void generatePropertiesFromGenericType(final Service service, final Resource genericType) { if (CollectionUtils.isEmpty(genericType.getProperties())) { return; } - final List genericTypePropertyList = genericType.getProperties().stream() - .map(PropertyDefinition::new) - .peek(propertyDefinition -> propertyDefinition.setUniqueId(null)) - .collect(Collectors.toList()); + final List genericTypePropertyList = genericType.getProperties().stream().map(PropertyDefinition::new) + .peek(propertyDefinition -> propertyDefinition.setUniqueId(null)).collect(Collectors.toList()); if (service.getProperties() == null) { service.setProperties(new ArrayList<>(genericTypePropertyList)); } else { List servicePropertyList = service.getProperties(); genericTypePropertyList.stream() - .filter(property -> servicePropertyList.stream() - .noneMatch(property1 -> property1.getName().equals(property.getName()))) + .filter(property -> servicePropertyList.stream().noneMatch(property1 -> property1.getName().equals(property.getName()))) .forEach(servicePropertyList::add); } - service.getProperties().forEach(propertyDefinition -> propertyDefinition.setUniqueId(null)); } @@ -941,15 +759,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { // 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) + 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()) { @@ -959,59 +777,53 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { 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 artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, + true); artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API); artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); } - service.setServiceApiArtifacts(artifactMap); } } @VisibleForTesting protected Either validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) { - try { - serviceValidator.validate(user,service,actionEnum); + serviceValidator.validate(user, service, actionEnum); } catch (ComponentException exp) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(exp); - componentsUtils.auditComponentAdmin(responseFormat, user, service, - AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE); + componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE); throw exp; } - 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); } public Either, ResponseFormat> validateServiceNameExists(String serviceName, String userId) { validateUserExists(userId); - - Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); + Either dataModelResponse = toscaOperationFacade + .validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); // DE242223 janusGraphDao.commit(); - if (dataModelResponse.isLeft()) { Map result = new HashMap<>(); result.put(IS_VALID, dataModelResponse.left().value()); log.debug("validation was successfully performed."); return Either.left(result); } - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); return Either.right(responseFormat); } @@ -1036,19 +848,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { user = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false); // validate user role validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null); - Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); if (storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + 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."); @@ -1056,30 +865,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } Service serviceToUpdate = validationRsponse.left().value(); // lock resource - lockComponent(serviceId, currentService, "Update Service Metadata"); try { - return toscaOperationFacade.updateToscaElement(serviceToUpdate) - .right() - .map(rf -> { - janusGraphDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); - log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); - return (componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - }) - .left() - .bind(c -> updateCatalogAndCommit(c)); - + return toscaOperationFacade.updateToscaElement(serviceToUpdate).right().map(rf -> { + janusGraphDao.rollback(); + BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); + log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); + return (componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + }).left().bind(c -> updateCatalogAndCommit(c)); } finally { graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); } } - private Either updateCatalogAndCommit(Service service){ - Either res = updateCatalog(service, ChangeTypeEnum.LIFECYCLE).left().map(s -> (Service)s); + private Either updateCatalogAndCommit(Service service) { + Either res = updateCatalog(service, ChangeTypeEnum.LIFECYCLE).left().map(s -> (Service) s); janusGraphDao.commit(); return res; - } public Set deleteForwardingPaths(String serviceId, Set pathIdsToDelete, User user, boolean lock) { @@ -1089,7 +891,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null); Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); if (storageStatus.isRight()) { - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""); } Service service = storageStatus.left().value(); Either, StorageOperationStatus> result = null; @@ -1098,27 +901,26 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service"); } catch (ComponentException e) { janusGraphDao.rollback(); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse - (storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""); } } - try{ - result = forwardingPathOperation.deleteForwardingPath(service ,pathIdsToDelete); + try { + result = forwardingPathOperation.deleteForwardingPath(service, pathIdsToDelete); if (result.isRight()) { log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, service.getName(), result.right().value()); janusGraphDao.rollback(); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse - (storageStatus.right().value(), ComponentTypeEnum.SERVICE)); + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE)); } janusGraphDao.commit(); log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, service.getSystemName()); - - } catch (ComponentException e){ + } catch (ComponentException e) { log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e); janusGraphDao.rollback(); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } finally { - graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); + graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); } return result.left().value(); } @@ -1127,19 +929,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Service serviceToDelete = new Service(); serviceToDelete.setUniqueId(serviceId); serviceToDelete.setForwardingPaths(new HashMap<>()); - pathIdsToDelete.forEach(pathIdToDelete -> serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition())); + pathIdsToDelete.forEach(pathIdToDelete -> serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition())); return serviceToDelete; } public Service updateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { - return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true,"updateForwardingPath", lock); + return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true, "updateForwardingPath", lock); } public Service createForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, false, "createForwardingPath", lock); } - private ForwardingPathDataDefinition getTrimmedValues(ForwardingPathDataDefinition path){ + 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()); @@ -1148,46 +950,38 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { dataDefinition.setPathElements(path.getPathElements()); dataDefinition.setDescription(path.getDescription()); dataDefinition.setToscaResourceName(path.getToscaResourceName()); - return dataDefinition; + return dataDefinition; } - private Service createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) { + private Service createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, + boolean lock) { validateUserAndRole(serviceUpdate, user, errorContext); - Map forwardingPaths = serviceUpdate.getForwardingPaths(); - - Map trimmedForwardingPaths = - forwardingPaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, - entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue())))); - - forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(), - serviceId, isUpdate); - + Map trimmedForwardingPaths = forwardingPaths.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue())))); + forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(), serviceId, isUpdate); Either serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId); - - if(serviceStorageOperationStatusEither.isRight()){ + if (serviceStorageOperationStatusEither.isRight()) { StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value(); log.debug("Failed to fetch service information by service id, error {}", errorStatus); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(errorStatus)); } Service storedService = serviceStorageOperationStatusEither.left().value(); - Either result; Component component = getForwardingPathOriginComponent(); final String toscaResourceName; - if ( component.getComponentType() == ComponentTypeEnum.RESOURCE) { + if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { toscaResourceName = ((Resource) component).getToscaResourceName(); } else { toscaResourceName = ""; } if (lock) { - lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service"); - log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName()); + lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service"); + log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName()); } Map resultMap = new HashMap<>(); try { trimmedForwardingPaths.values().forEach(fp -> fp.setToscaResourceName(toscaResourceName)); - populateForwardingPaths(serviceId, isUpdate, trimmedForwardingPaths, resultMap); janusGraphDao.commit(); } finally { @@ -1199,7 +993,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } private Component getForwardingPathOriginComponent() { - Either forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME); + 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); @@ -1208,7 +1003,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return forwardingPathOrigin.left().value(); } - private void populateForwardingPaths(String serviceId, boolean isUpdate, Map trimmedForwardingPaths, Map resultMap) { + private void populateForwardingPaths(String serviceId, boolean isUpdate, Map trimmedForwardingPaths, + Map resultMap) { Either result; try { for (ForwardingPathDataDefinition forwardingPathDataDefinition : trimmedForwardingPaths.values()) { @@ -1219,24 +1015,22 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } if (result.isRight()) { janusGraphDao.rollback(); - throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), - "")); + throw new ByResponseFormatComponentException(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), "")); } else { ForwardingPathDataDefinition fpDataDefinition = result.left().value(); resultMap.put(fpDataDefinition.getUniqueId(), forwardingPathDataDefinition); } } - } catch (ComponentException e) { janusGraphDao.rollback(); - log.error("Exception occurred during add or update forwarding path property values: {}", - e.getMessage(), e); + log.error("Exception occurred during add or update forwarding path property values: {}", e.getMessage(), e); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } } - private Service createServiceWithForwardingPathForResponse(String serviceId, Map forwardingPathDataDefinitionMap) { + private Service createServiceWithForwardingPathForResponse(String serviceId, + Map forwardingPathDataDefinitionMap) { Service service = new Service(); service.setUniqueId(serviceId); service.setForwardingPaths(forwardingPathDataDefinitionMap); @@ -1250,87 +1044,70 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @VisibleForTesting Either validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) { - try { boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion()); - Either response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, UPDATE_SERVICE_METADATA); + Either response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, + UPDATE_SERVICE_METADATA); if (response.isRight()) { ResponseFormat errorResponse = response.right().value(); return Either.right(errorResponse); } - verifyValuesAreIdentical(serviceUpdate.getCreatorUserId(), currentService.getCreatorUserId(), "creatorUserId"); verifyValuesAreIdentical(serviceUpdate.getCreatorFullName(), currentService.getCreatorFullName(), "creatorFullName"); verifyValuesAreIdentical(serviceUpdate.getLastUpdaterUserId(), currentService.getLastUpdaterUserId(), "lastUpdaterUserId"); verifyValuesAreIdentical(serviceUpdate.getLastUpdaterFullName(), currentService.getLastUpdaterFullName(), "lastUpdaterFullName"); - response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null); if (response.isRight()) { return Either.right(response.right().value()); } - verifyValuesAreIdentical(serviceUpdate.getDistributionStatus(), currentService.getDistributionStatus(), "distributionStatus"); - if (serviceUpdate.getProjectCode() != null) { response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA); if (response.isRight()) { return Either.right(response.right().value()); } } - response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, UPDATE_SERVICE_METADATA); if (response.isRight()) { return Either.right(response.right().value()); } - verifyValuesAreIdentical(serviceUpdate.getCreationDate(), currentService.getCreationDate(), "creationDate"); verifyValuesAreIdentical(serviceUpdate.getVersion(), currentService.getVersion(), "version"); - response = validateAndUpdateDescription(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA); if (response.isRight()) { return Either.right(response.right().value()); } - response = validateAndUpdateTags(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA); if (response.isRight()) { return Either.right(response.right().value()); } - response = validateAndUpdateContactId(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA); if (response.isRight()) { return Either.right(response.right().value()); } - verifyValuesAreIdentical(serviceUpdate.getLastUpdateDate(), currentService.getLastUpdateDate(), "lastUpdateDate"); verifyValuesAreIdentical(serviceUpdate.getLifecycleState(), currentService.getLifecycleState(), "lifecycleState"); verifyValuesAreIdentical(serviceUpdate.isHighestVersion(), currentService.isHighestVersion(), "isHighestVersion"); verifyValuesAreIdentical(serviceUpdate.getUUID(), currentService.getUUID(), "uuid"); - validateAndUpdateServiceType(currentService, serviceUpdate); validateAndUpdateServiceFunction(currentService, serviceUpdate); - response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA); if (response.isRight()) { return Either.right(response.right().value()); } - response = validateAndUpdateInstantiationTypeValue(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA); if (response.isRight()) { return Either.right(response.right().value()); } - verifyValuesAreIdentical(serviceUpdate.getInvariantUUID(), currentService.getInvariantUUID(), "invariantUUID"); - validateAndUpdateEcompNaming(currentService, serviceUpdate); - currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext()); currentService.setCategorySpecificMetadata(serviceUpdate.getCategorySpecificMetadata()); return Either.left(currentService); - } catch (ComponentException exception) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(exception); - componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, - AuditingActionEnum.UPDATE_SERVICE_METADATA, ComponentTypeEnum.SERVICE); + componentsUtils + .auditComponentAdmin(responseFormat, user, serviceUpdate, AuditingActionEnum.UPDATE_SERVICE_METADATA, ComponentTypeEnum.SERVICE); return Either.right(responseFormat); } } @@ -1358,7 +1135,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } } - private Either validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { + private Either validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, + AuditingActionEnum audatingAction) { String contactIdUpdated = serviceUpdate.getContactId(); String contactIdCurrent = currentService.getContactId(); if (!contactIdCurrent.equals(contactIdUpdated)) { @@ -1368,7 +1146,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private Either validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { + private Either validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, + AuditingActionEnum audatingAction) { List tagsUpdated = serviceUpdate.getTags(); List tagsCurrent = currentService.getTags(); if (tagsUpdated == null || tagsUpdated.isEmpty()) { @@ -1376,7 +1155,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, audatingAction, ComponentTypeEnum.SERVICE); return Either.right(responseFormat); } - if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { componentTagsValidator.validateAndCorrectField(user, serviceUpdate, audatingAction); currentService.setTags(tagsUpdated); @@ -1384,7 +1162,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private Either validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { + private Either validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, + AuditingActionEnum audatingAction) { String descriptionUpdated = serviceUpdate.getDescription(); String descriptionCurrent = currentService.getDescription(); if (!descriptionCurrent.equals(descriptionUpdated)) { @@ -1394,12 +1173,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private Either validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { + private Either validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, + AuditingActionEnum audatingAction) { String projectCodeUpdated = serviceUpdate.getProjectCode(); String projectCodeCurrent = currentService.getProjectCode(); - if (StringUtils.isEmpty(projectCodeCurrent) - || !projectCodeCurrent.equals(projectCodeUpdated)) { - + if (StringUtils.isEmpty(projectCodeCurrent) || !projectCodeCurrent.equals(projectCodeUpdated)) { try { componentProjectCodeValidator.validateAndCorrectField(user, serviceUpdate, audatingAction); } catch (ComponentException exp) { @@ -1407,12 +1185,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(errorRespons); } currentService.setProjectCode(projectCodeUpdated); - } return Either.left(true); } - private Either validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + 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)) { @@ -1428,7 +1206,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private Either validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) { + 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)) { @@ -1440,9 +1219,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(exp.getResponseFormat()); } currentService.setName(serviceNameUpdated); - currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated)); - currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(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); @@ -1470,7 +1250,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } } - private Either validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { + private Either validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, + AuditingActionEnum auditingAction) { String updatedServiceRole = updatedService.getServiceRole(); String currentServiceRole = currentService.getServiceRole(); if (!currentServiceRole.equals(updatedServiceRole)) { @@ -1486,8 +1267,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private Either validateAndUpdateInstantiationTypeValue(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { - String updatedInstaType= updatedService.getInstantiationType(); + private Either validateAndUpdateInstantiationTypeValue(User user, Service currentService, Service updatedService, + AuditingActionEnum auditingAction) { + String updatedInstaType = updatedService.getInstantiationType(); String currentInstaType = currentService.getInstantiationType(); if (!currentInstaType.equals(updatedInstaType)) { try { @@ -1502,7 +1284,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private Either validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + private Either validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, + boolean hasBeenCertified, AuditingActionEnum audatingAction) { try { List categoryUpdated = serviceUpdate.getCategories(); List categoryCurrent = currentService.getCategories(); @@ -1520,32 +1303,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.right(exp.getResponseFormat()); } return Either.left(true); - } public Either getServiceComponentsRelations(String serviceId, User user) { Either serviceResponseFormatEither = getService(serviceId, user); - if (serviceResponseFormatEither.isRight()){ + if (serviceResponseFormatEither.isRight()) { return Either.right(serviceResponseFormatEither.right().value()); } - final ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(serviceResponseFormatEither.left().value()); + final ServiceRelations serviceRelations = new ForwardingPathUtils() + .convertServiceToServiceRelations(serviceResponseFormatEither.left().value()); return Either.left(serviceRelations); - - } public ResponseFormat deleteService(String serviceId, User user) { ResponseFormat responseFormat; - validateUserExists(user); 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; try { lockComponent(service, "Mark service to delete"); @@ -1557,9 +1335,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); } return responseFormat; - }catch (ComponentException e){ + } catch (ComponentException e) { return e.getResponseFormat(); - }finally { + } finally { if (result == null || result != StorageOperationStatus.OK) { log.warn("operation failed. do rollback"); BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); @@ -1577,15 +1355,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String ecompErrorContext = "delete service"; validateUserNotEmpty(user, ecompErrorContext); user = validateUserExists(user); - Either getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId()); if (getResult.isRight()) { return getResult.right().value(); } Service service = getResult.left().value(); - StorageOperationStatus result = StorageOperationStatus.OK; - try { lockComponent(service, "Mark service to delete"); result = markComponentToDelete(service); @@ -1596,11 +1371,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); } return responseFormat; - - }catch (ComponentException e){ + } catch (ComponentException e) { result = StorageOperationStatus.GENERAL_ERROR; return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - }finally { + } finally { if (result == null || result != StorageOperationStatus.OK) { log.warn("operation failed. do rollback"); BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); @@ -1617,30 +1391,29 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { String ecompErrorContext = "Get service"; validateUserNotEmpty(user, ecompErrorContext); validateUserExists(user); - 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)); + 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)); + 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) { validateUserExists(userId); - Either storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion); + 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)); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), + serviceName)); } Service service = storageStatus.left().value(); return Either.left(service); @@ -1651,15 +1424,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { // 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) + if (artifactMap == null) { artifactMap = new HashMap<>(); - - Map informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts(); + } + 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()) { @@ -1669,26 +1443,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { 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); + 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); - + 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); @@ -1702,21 +1473,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return configuredEnvName; } - public Either activateServiceOnTenantEnvironment(String serviceId, String envId, User modifier, ServiceDistributionReqInfo data) { - - Either activationRequestInformationEither = serviceDistributionValidation.validateActivateServiceRequest(serviceId, envId, modifier, data); + 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(); - String did = ThreadLocalsHolder.getUuid(); Service service = activationRequestInformation.getServiceToActivate(); return buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier); } - private Either buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) { + private 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); @@ -1731,21 +1502,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } public Either activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) { - User user = validateUserExists(modifier.getUserId()); validateUserRole(user, Collections.singletonList(Role.DESIGNER)); Either result; ResponseFormat response; Service updatedService; String did = ThreadLocalsHolder.getUuid(); - // DE194021 + // DE194021 String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); if (configuredEnvName != null && !configuredEnvName.equals(envName)) { 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) { @@ -1754,16 +1523,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { 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); + response = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId); componentsUtils.auditComponent(response, user, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, - new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()), - ResourceVersionInfo.newBuilder() - .build(), - did); + new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()), ResourceVersionInfo.newBuilder().build(), did); return Either.right(response); } Service service = serviceRes.left().value(); @@ -1773,7 +1539,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } 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()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName()); return Either.right(responseFormat); } String dcurrStatus = service.getDistributionStatus().name(); @@ -1783,7 +1550,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, null); ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user); if (notifyServiceResponse == ActionStatus.OK) { - Either updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED); + Either updateStateRes = updateDistributionStatusForActivation(service, user, + DistributionStatusEnum.DISTRIBUTED); if (updateStateRes.isLeft() && updateStateRes.left().value() != null) { updatedService = updateStateRes.left().value(); updatedStatus = updatedService.getDistributionStatus().name(); @@ -1801,28 +1569,22 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { result = Either.right(response); } } else { - response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution, ComponentTypeEnum.SERVICE), envName); + response = componentsUtils + .getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution, ComponentTypeEnum.SERVICE), envName); result = Either.right(response); } componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, - new ResourceCommonInfo(service.getName(),ComponentTypeEnum.SERVICE.getValue()), - ResourceVersionInfo.newBuilder() - .distributionStatus(dcurrStatus) - .build(), - ResourceVersionInfo.newBuilder() - .distributionStatus(updatedStatus) - .build(), - null, null, did); + new ResourceCommonInfo(service.getName(), ComponentTypeEnum.SERVICE.getValue()), + ResourceVersionInfo.newBuilder().distributionStatus(dcurrStatus).build(), + ResourceVersionInfo.newBuilder().distributionStatus(updatedStatus).build(), null, null, did); return result; } // convert to private after deletion of temp url public Either updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) { - validateUserExists(user.getUserId()); - String serviceId = service.getUniqueId(); - lockComponent(serviceId, service, "updateDistributionStatusForActivation"); + lockComponent(serviceId, service, "updateDistributionStatusForActivation"); try { Either result = toscaOperationFacade.updateDistributionStatus(service, user, state); if (result.isRight()) { @@ -1840,38 +1602,33 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } public Either markDistributionAsDeployed(String serviceId, String did, User user) { - validateUserExists(user.getUserId()); 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); + 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), ""); - + ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, + componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), ""); return Either.right(responseFormat); } - Service service = getServiceResponse.left().value(); user = validateRoleForDeploy(did, user, auditAction, service); 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); - + // 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) { + 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 VfModuleArtifactGenerator(modifier, ri, service, shouldLock, inTransaction)); } @@ -1880,25 +1637,25 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private List collectGroupsInstanceForCompInstance(ComponentInstance currVF) { Map deploymentArtifacts = currVF.getDeploymentArtifacts(); - if(currVF.getGroupInstances() != null){ + if (currVF.getGroupInstances() != null) { currVF.getGroupInstances().forEach(gi -> gi.alignArtifactsUuid(deploymentArtifacts)); } return currVF.getGroupInstances(); } - private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, Wrapper payloadWrapper, Wrapper responseWrapper) { + private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, Wrapper payloadWrapper, + Wrapper responseWrapper) { ArtifactDefinition vfModuleAertifact = null; if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) { - final Optional optionalVfModuleArtifact = - currVF.getDeploymentArtifacts().values().stream() - .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.getType())) - .findAny(); + final Optional optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.getType())).findAny(); if (optionalVfModuleArtifact.isPresent()) { vfModuleAertifact = optionalVfModuleArtifact.get(); } } if (vfModuleAertifact == null) { - Either createVfModuleArtifact = createVfModuleArtifact(currVF, service, payloadWrapper.getInnerElement()); + Either createVfModuleArtifact = createVfModuleArtifact(currVF, service, + payloadWrapper.getInnerElement()); if (createVfModuleArtifact.isLeft()) { vfModuleAertifact = createVfModuleArtifact.left().value(); } else { @@ -1916,16 +1673,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { vfModulePayloads.add(modulePayload); } vfModulePayloads.sort(VfModuleArtifactPayload::compareByGroupName); - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - String vfModulePayloadString = gson.toJson(vfModulePayloads); payloadWrapper.setInnerElement(vfModulePayloadString); } - } - private Either generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock, boolean inTransaction) { + private Either generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, + Service service, boolean shouldLock, boolean inTransaction) { ArtifactDefinition vfModuleArtifact = null; Wrapper responseWrapper = new Wrapper<>(); Wrapper payloadWrapper = new Wrapper<>(); @@ -1937,23 +1692,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { vfModuleArtifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, payloadWrapper, responseWrapper); } if (responseWrapper.isEmpty() && vfModuleArtifact != null) { - vfModuleArtifact = fillVfModulePayload(modifier, currVFInstance, vfModuleArtifact, shouldLock, inTransaction, payloadWrapper, responseWrapper, service); + vfModuleArtifact = fillVfModulePayload(modifier, currVFInstance, vfModuleArtifact, shouldLock, inTransaction, payloadWrapper, + responseWrapper, service); } - Either result; if (responseWrapper.isEmpty()) { result = Either.left(vfModuleArtifact); } 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) { + 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()); + 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 { @@ -1962,15 +1721,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (result == null) { result = vfModuleArtifact; } - return result; } - private Either createVfModuleArtifact(ComponentInstance currVF, Service service, String vfModulePayloadString) { - + private Either createVfModuleArtifact(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()); @@ -1983,54 +1740,54 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes()); } vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum); - - Either addArtifactToComponent = artifactToscaOperation.addArtifactToComponent( - vfModuleArtifactDefinition, service, NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); - + Either addArtifactToComponent = artifactToscaOperation + .addArtifactToComponent(vfModuleArtifactDefinition, service, NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); Either result; if (addArtifactToComponent.isLeft()) { result = Either.left(addArtifactToComponent.left().value()); } else { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtifactToComponent.right().value()))); + result = Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtifactToComponent.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()); - + // 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) { - + 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()); + List> artifactGenList = service.getComponentInstances().stream() + .flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList()); if (artifactGenList != null && !artifactGenList.isEmpty()) { Either callRes = checkDeploymentArtifact(artifactGenList); - if (callRes != null) return callRes; + if (callRes != null) { + return callRes; + } } } Either storageStatus = toscaOperationFacade.getToscaFullElement(service.getUniqueId()); if (storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); } - Service currentService = storageStatus.left().value(); - return Either.left(currentService); - } private Either checkDeploymentArtifact(List> artifactGenList) { @@ -2050,61 +1807,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return null; } - abstract class ArtifactGenerator implements Callable> { - - } - - @Getter - class HeatEnvArtifactGenerator extends ArtifactGenerator { - private ArtifactDefinition artifactDefinition; - private Service service; - private String resourceInstanceName; - private User modifier; - private String instanceId; - private boolean shouldLock; - private 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); - } - - } - - class VfModuleArtifactGenerator 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 VfModuleArtifactGenerator(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 distributionId, User user, AuditingActionEnum auditAction, Service service) { + private synchronized Either checkDistributionAndDeploy(String distributionId, User user, AuditingActionEnum auditAction, + Service service) { boolean isDeployed = isDistributionDeployed(distributionId); if (isDeployed) { return Either.left(service); @@ -2113,15 +1817,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (distributionSuccess.isRight()) { return Either.right(distributionSuccess.right().value()); } - log.debug("mark distribution {} as deployed - success", distributionId); - componentsUtils.auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), distributionId, STATUS_DEPLOYED, "OK", user); + componentsUtils + .auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), distributionId, STATUS_DEPLOYED, "OK", + user); return Either.left(service); } private boolean isDistributionDeployed(String distributionId) { - Either, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(distributionId, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED); - + Either, ActionStatus> alreadyDeployed = auditCassandraDao + .getDistributionDeployByStatus(distributionId, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED); boolean isDeployed = false; if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) { // already deployed @@ -2132,16 +1837,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } 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()); + 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); @@ -2157,14 +1860,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { break; } } - // get all "DNotify" records for this distribution - Either, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); + 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) { @@ -2174,10 +1876,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { 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); @@ -2186,17 +1886,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) { - + 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(service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user); + componentsUtils + .auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), + message, user); } else { componentsUtils.auditServiceDistributionDeployed("", "", "", did, error.getStatus().toString(), message, user); } @@ -2209,9 +1910,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { List roles = new ArrayList<>(); roles.add(Role.ADMIN); roles.add(Role.DESIGNER); - try{ + try { validateUserRole(user, service, roles, auditAction, null); - } catch (ByActionStatusComponentException e){ + } catch (ByActionStatusComponentException e) { log.info("role {} is not allowed to perform this action", user.getRole()); auditDeployError(did, user, auditAction, service, e.getActionStatus()); throw e; @@ -2221,28 +1922,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @Override public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - if(component instanceof Service){ + if (component instanceof Service) { Service service = (Service) component; Map artifactMap = service.getDeploymentArtifacts(); if (artifactMap == null) { artifactMap = new HashMap<>(); } service.setDeploymentArtifacts(artifactMap); - }else if(component instanceof Resource){ + } else if (component instanceof Resource) { Resource resource = (Resource) component; Map artifactMap = resource.getDeploymentArtifacts(); if (artifactMap == null) { artifactMap = new HashMap<>(); } - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration().getDeploymentResourceArtifacts(); + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getDeploymentResourceArtifacts(); if (deploymentResourceArtifacts != null) { Map finalArtifactMap = artifactMap; - deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v)); + deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v)); } resource.setDeploymentArtifacts(artifactMap); } - } private void processDeploymentResourceArtifacts(User user, Resource resource, Map artifactMap, String k, Object v) { @@ -2254,15 +1954,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return; } } else { - log.info("resource types for artifact placeholder {} were not defined. default is all resources", - k); + log.info("resource types for artifact placeholder {} were not defined. default is all resources", k); } if (artifactsBusinessLogic != null) { - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resource.getUniqueId(), k, (Map) v, - user, ArtifactGroupTypeEnum.DEPLOYMENT); - if (artifactDefinition != null - && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { + ArtifactDefinition artifactDefinition = artifactsBusinessLogic + .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map) v, user, ArtifactGroupTypeEnum.DEPLOYMENT); + if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); } } @@ -2274,7 +1971,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(HealthCheckBusinessLogic.class); } @@ -2286,16 +1984,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @Override public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId) { - validateUserExists(userId); Either getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); if (getComponentRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value())); return Either.right(responseFormat); } - List componentInstances = getComponentRes.left().value().getComponentInstances(); - return Either.left(componentInstances); } @@ -2305,11 +2001,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } /** - * 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 - * + * 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 */ - public Either, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List newProperties) { - + public Either, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, + String componentInstanceId, String groupInstanceId, + List newProperties) { Either, ResponseFormat> actionResult = null; Either, ResponseFormat> validateUserAndComponentRes; Component component = null; @@ -2332,9 +2029,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } } if (actionResult == null) { - actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties); + 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()); + 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) { @@ -2348,8 +2047,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return actionResult; } - private Either, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List newProperties) { - + private Either, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, + String componentInstanceId, + String groupInstanceId, + List newProperties) { Either, ResponseFormat> actionResult = null; Either, ResponseFormat> findGroupInstanceRes; Either, ResponseFormat> updateParentsModificationTimeRes; @@ -2366,18 +2067,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { if (actionResult == null) { oldGroupInstance = findGroupInstanceRes.left().value().getValue(); relatedComponentInstance = findGroupInstanceRes.left().value().getKey(); - updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties); + updateGroupInstanceResult = groupBusinessLogic + .validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties); if (updateGroupInstanceResult.isRight()) { - log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update group instance {} property values. ", oldGroupInstance.getName()); + log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - 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); + updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, + updatedGroupInstance, inTransaction); if (updateParentsModificationTimeRes.isRight()) { - log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update modification time for group instance {}. ", oldGroupInstance.getName()); + log.debug( + "#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update modification time for group instance {}. ", + oldGroupInstance.getName()); actionResult = Either.right(updateParentsModificationTimeRes.right().value()); } } @@ -2388,30 +2094,33 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return actionResult; } - private Either, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, - boolean inTranscation) { - + private Either, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid( + Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, boolean inTranscation) { Either, ResponseFormat> actionResult; Either serviceMetadataUpdateResult; - Either updateComponentInstanceRes = componentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance, + 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()); + 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); 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()))); + 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())); + 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; User currUser = null; Component component = null; @@ -2425,7 +2134,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { try { component = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null); if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) { - log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId()); + log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(), + component.getCreatorUserId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } } catch (ComponentException e) { @@ -2433,27 +2143,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { result = Either.right(e.getResponseFormat()); } } - if (result == null) { result = Either.left(new ImmutablePair<>(component, currUser)); } return result; } - private Either, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) { - + 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 (isNotEmpty(foundComponentInstance.getGroupInstances())) { - groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null); + actionResult = Either.right(componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", + component.getName())); + } else if (isNotEmpty(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())); + actionResult = Either.right(componentsUtils + .getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, + foundComponentInstance.getName())); } } if (actionResult == null) { @@ -2465,7 +2179,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) { ComponentInstance componentInstance = null; if (isNotEmpty(component.getComponentInstances())) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); + componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst() + .orElse(null); } return componentInstance; } @@ -2479,28 +2194,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(user); } - public Either getUiComponentDataTransferByComponentId(String serviceId, List dataParamsToReturn) { - + public Either getUiComponentDataTransferByComponentId(String serviceId, + List dataParamsToReturn) { ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn); paramsToReturn.setIgnoreComponentInstancesProperties(false); Either serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToReturn); - if (serviceResultEither.isRight()) { - if(serviceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) { + if (serviceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) { log.debug("#getUiComponentDataTransferByComponentId - Failed to find service with id {} ", serviceId); return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId)); } - log.debug("#getUiComponentDataTransferByComponentId - failed to get service by id {} with filters {}", serviceId, dataParamsToReturn); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); + return Either.right( + componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); } - Service service = serviceResultEither.left().value(); - if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) { - ListUtils.emptyIfNull(service.getInputs()) - .forEach(input -> input.setConstraints(setInputConstraint(input))); - } - + if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) { + ListUtils.emptyIfNull(service.getInputs()).forEach(input -> input.setConstraints(setInputConstraint(input))); + } UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn); return Either.left(dataTransfer); } @@ -2514,4 +2225,62 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { Either latestByName = toscaOperationFacade.getLatestByServiceName(serviceName); return latestByName.isLeft(); } + + abstract class ArtifactGenerator implements Callable> { + + } + + @Getter + class HeatEnvArtifactGenerator extends ArtifactGenerator { + + private ArtifactDefinition artifactDefinition; + private Service service; + private String resourceInstanceName; + private User modifier; + private String instanceId; + private boolean shouldLock; + private 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); + } + } + + class VfModuleArtifactGenerator extends ArtifactGenerator { + + boolean shouldLock; + boolean inTransaction; + private User user; + private ComponentInstance componentInstance; + private Service service; + + private VfModuleArtifactGenerator(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; + } + + @Override + public Either call() throws Exception { + return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock, inTransaction); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java index 0ffceda8e8..2956abfe1b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java @@ -15,7 +15,26 @@ */ package org.openecomp.sdc.be.components.impl; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement; +import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue; +import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; + import fj.data.Either; +import java.util.ArrayList; +import java.util.Collection; +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.Optional; +import java.util.Set; +import java.util.regex.Pattern; import lombok.Getter; import lombok.Setter; import org.apache.commons.collections.CollectionUtils; @@ -117,32 +136,11 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.yaml.snakeyaml.Yaml; -import java.util.ArrayList; -import java.util.Collection; -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.Optional; -import java.util.Set; -import java.util.regex.Pattern; - -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toMap; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement; -import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue; -import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; - @Getter @Setter @org.springframework.stereotype.Component("serviceImportBusinessLogic") public class ServiceImportBusinessLogic { - private final UiComponentDataConverter uiComponentDataConverter; private static final String INITIAL_VERSION = "0.1"; private static final String CREATE_RESOURCE = "Create Resource"; private static final String IN_RESOURCE = " in resource {} "; @@ -153,25 +151,18 @@ public class ServiceImportBusinessLogic { private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate"; private static final String CATEGORY_IS_EMPTY = "Resource category is empty"; - - @Autowired - private ServiceBusinessLogic serviceBusinessLogic; - - public ServiceBusinessLogic getServiceBusinessLogic() { - return serviceBusinessLogic; - } - - public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) { - this.serviceBusinessLogic = serviceBusinessLogic; - } - - @Autowired - private CsarBusinessLogic csarBusinessLogic; + private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class); + private final UiComponentDataConverter uiComponentDataConverter; + private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; @Autowired protected ComponentsUtils componentsUtils; @Autowired protected ToscaOperationFacade toscaOperationFacade; @Autowired + private ServiceBusinessLogic serviceBusinessLogic; + @Autowired + private CsarBusinessLogic csarBusinessLogic; + @Autowired private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic; @Autowired private LifecycleBusinessLogic lifecycleBusinessLogic; @@ -182,33 +173,30 @@ public class ServiceImportBusinessLogic { @Autowired private ServiceImportParseLogic serviceImportParseLogic; - private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class); - @Autowired - public ServiceImportBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsBusinessLogic artifactsBusinessLogic, - IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, + public ServiceImportBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, + InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsBusinessLogic artifactsBusinessLogic, IDistributionEngine distributionEngine, + ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator, UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation, NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation, - ComponentContactIdValidator componentContactIdValidator, - ComponentNameValidator componentNameValidator, - ComponentTagsValidator componentTagsValidator, - ComponentValidator componentValidator, - ComponentIconValidator componentIconValidator, - ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator, ComponentDescriptionValidator componentDescriptionValidator) { this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; this.uiComponentDataConverter = uiComponentDataConverter; } - private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + public ServiceBusinessLogic getServiceBusinessLogic() { + return serviceBusinessLogic; + } + + public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) { + this.serviceBusinessLogic = serviceBusinessLogic; + } public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map csarUIPayload, String payloadName) { @@ -221,13 +209,10 @@ public class ServiceImportBusinessLogic { service.setInstantiationType("A-la-carte"); service.setEnvironmentContext("General_Revenue-Bearing"); service.setEcompGeneratedNaming(true); - try { serviceBusinessLogic.validateServiceBeforeCreate(service, user, auditingAction); - log.debug("enter createService,validateServiceBeforeCreate success"); String csarUUID = payloadName == null ? service.getCsarUUID() : payloadName; - log.debug("enter createService,get csarUUID:{}", csarUUID); csarBusinessLogic.validateCsarBeforeCreate(service, csarUUID); log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); @@ -242,36 +227,30 @@ public class ServiceImportBusinessLogic { log.trace("************* created successfully from YAML, resource TOSCA "); try { CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID); - Map nodeTypesInfo = csarInfo.extractNodeTypesInfo(); Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic - .findNodeTypesArtifactsToHandle( - nodeTypesInfo, csarInfo, service); + .findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, service); if (findNodeTypesArtifactsToHandleRes.isRight()) { - log.debug("failed to find node types for update with artifacts during import csar {}. ", - csarInfo.getCsarUUID()); + log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID()); throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value()); } - return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), - nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, - null); + return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, + findNodeTypesArtifactsToHandleRes.left().value(), true, false, null); } catch (Exception e) { log.debug("Exception occured when createServiceFromCsar,error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } } - protected Service createServiceFromYaml(Service service, String topologyTemplateYaml, - String yamlName, Map nodeTypesInfo, CsarInfo csarInfo, + protected Service createServiceFromYaml(Service service, String topologyTemplateYaml, String yamlName, Map nodeTypesInfo, + CsarInfo csarInfo, Map>> nodeTypesArtifactsToCreate, boolean shouldLock, boolean inTransaction, String nodeName) { - List createdArtifacts = new ArrayList<>(); Service createdService; CreateServiceFromYamlParameter csfyp = new CreateServiceFromYamlParameter(); try { - ParsedToscaYamlInfo - parsedToscaYamlInfo = csarBusinessLogic + ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service); if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances())) { throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); @@ -284,7 +263,6 @@ public class ServiceImportBusinessLogic { csfyp.setNodeTypesInfo(nodeTypesInfo); csfyp.setCsarInfo(csarInfo); csfyp.setNodeName(nodeName); - createdService = createServiceAndRIsFromYaml(service, false, nodeTypesArtifactsToCreate, shouldLock, inTransaction, csfyp); log.debug("#createResourceFromYaml - The resource {} has been created ", service.getName()); } catch (ComponentException e) { @@ -300,7 +278,6 @@ public class ServiceImportBusinessLogic { protected Service createServiceAndRIsFromYaml(Service service, boolean isNormative, Map>> nodeTypesArtifactsToCreate, boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp) { - List nodeTypesNewCreatedArtifacts = new ArrayList<>(); String yamlName = csfyp.getYamlName(); ParsedToscaYamlInfo parsedToscaYamlInfo = csfyp.getParsedToscaYamlInfo(); @@ -309,7 +286,6 @@ public class ServiceImportBusinessLogic { Map nodeTypesInfo = csfyp.getNodeTypesInfo(); CsarInfo csarInfo = csfyp.getCsarInfo(); String nodeName = csfyp.getNodeName(); - if (shouldLock) { Either lockResult = serviceBusinessLogic.lockComponentByName(service.getSystemName(), service, CREATE_RESOURCE); if (lockResult.isRight()) { @@ -322,18 +298,13 @@ public class ServiceImportBusinessLogic { log.trace("************* createResourceFromYaml before full create resource {}", yamlName); service = serviceImportParseLogic.createServiceTransaction(service, csarInfo.getModifier(), isNormative); log.trace("************* Going to add inputs from yaml {}", yamlName); - Map inputs = parsedToscaYamlInfo.getInputs(); service = serviceImportParseLogic.createInputsOnService(service, inputs); log.trace("************* Finish to add inputs from yaml {}", yamlName); - - Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo - .getInstances(); + Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances(); log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); - - service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap, - topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, - nodeTypesArtifactsToCreate, nodeName); + service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap, topologyTemplateYaml, + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName); log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); Either, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName()); @@ -343,13 +314,11 @@ public class ServiceImportBusinessLogic { } 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(service, groups); if (createGroupsOnResource.isRight()) { serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts); @@ -357,13 +326,9 @@ public class ServiceImportBusinessLogic { } service = createGroupsOnResource.left().value(); log.trace("************* Going to add artifacts from yaml {}", yamlName); - - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, - nodeTypesArtifactsToCreate); - - Either createArtifactsEither = createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, - csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate); + Either createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, + createdArtifacts, yamlName, csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); if (createArtifactsEither.isRight()) { serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(createArtifactsEither.right().value()); @@ -379,27 +344,24 @@ public class ServiceImportBusinessLogic { serviceBusinessLogic.janusGraphDao.commit(); } if (shouldLock) { - serviceBusinessLogic.graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), - NodeTypeEnum.Resource); + serviceBusinessLogic.graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Resource); } } } - protected Either createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum operation, List createdArtifacts, - String yamlFileName, CsarInfo csarInfo, Resource preparedResource, - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { - + protected Either createOrUpdateArtifacts(ArtifactsBusinessLogic.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.VF) { if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) { - Either, ResponseFormat> handleNodeTypeArtifactsRes = - handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), - inTransaction, true); + Either, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource, + nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true); if (handleNodeTypeArtifactsRes.isRight()) { return Either.right(handleNodeTypeArtifactsRes.right().value()); } @@ -416,28 +378,25 @@ public class ServiceImportBusinessLogic { return Either.left(resource); } - protected Either handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, - List createdArtifacts, + protected Either handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, boolean inTransaction) { if (csarInfo.getCsar() != null) { createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction); - - Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, - createdArtifacts, shouldLock, inTransaction, artifactOperation); + 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); + 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()) { return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction, artifacsMetaCsarStatus); @@ -465,17 +424,13 @@ public class ServiceImportBusinessLogic { } } } - 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, true, 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, + 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, true, 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, true, shouldLock, inTransaction); } protected Either getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo, @@ -489,12 +444,11 @@ public class ServiceImportBusinessLogic { Either createArtifactsFromCsar; if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic - .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, - createdArtifacts); + .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts); } else { Either result = csarArtifactsAndGroupsBusinessLogic - .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, - createdArtifacts, shouldLock, inTransaction); + .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, + inTransaction); if ((result.left().value() instanceof Resource) && result.isLeft()) { Resource service1 = (Resource) result.left().value(); createArtifactsFromCsar = Either.left(service1); @@ -522,11 +476,10 @@ public class ServiceImportBusinessLogic { try { Either, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages); if (artifactPathAndNameList.isRight()) { - return Either.right(getComponentsUtils().getResponseFormatByArtifactId( - ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value())); + return Either.right( + getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value())); } EnumMap> vfCsarArtifactsToHandle = null; - if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class); vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value()); @@ -558,30 +511,21 @@ public class ServiceImportBusinessLogic { protected Either createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, List createdArtifacts, boolean shouldLock, - boolean inTransaction, - ArtifactOperationInfo artifactOperation) { + boolean inTransaction, ArtifactOperationInfo artifactOperation) { return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation); } protected Either processCsarArtifacts(CsarInfo csarInfo, Component comp, List createdArtifacts, boolean shouldLock, - boolean inTransaction, - Either resStatus, + boolean inTransaction, Either resStatus, EnumMap> vfCsarArtifactsToHandle) { for (Map.Entry> currArtifactOperationPair : vfCsarArtifactsToHandle .entrySet()) { - Optional optionalCreateInDBError = - currArtifactOperationPair.getValue().stream() - .map(e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), - e.getArtifactName(), e.getArtifactType(), - e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), - CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), - new ArtifactOperationInfo(false, false, - currArtifactOperationPair.getKey()), - createdArtifacts, e.isFromCsar(), shouldLock, inTransaction)) - .filter(Either::isRight). - map(e -> e.right().value()). - findAny(); + Optional optionalCreateInDBError = currArtifactOperationPair.getValue().stream().map( + e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(), + e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), + new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, e.isFromCsar(), shouldLock, + inTransaction)).filter(Either::isRight).map(e -> e.right().value()).findAny(); if (optionalCreateInDBError.isPresent()) { resStatus = Either.right(optionalCreateInDBError.get()); break; @@ -590,17 +534,14 @@ public class ServiceImportBusinessLogic { return resStatus; } - protected Either createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo, - String artifactPath, String artifactFileName, String artifactType, - ArtifactGroupTypeEnum artifactGroupType, - String artifactLabel, String artifactDisplayName, - String artifactDescription, String artifactId, - ArtifactOperationInfo operation, + protected Either createOrUpdateSingleNonMetaArtifact(Component component, 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) { + boolean shouldLock, boolean inTransaction) { byte[] artifactFileBytes = null; - if (csarInfo.getCsar().containsKey(artifactPath)) { artifactFileBytes = csarInfo.getCsar().get(artifactPath); } @@ -609,33 +550,27 @@ public class ServiceImportBusinessLogic { || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) { if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) { Either handleDelete = serviceBusinessLogic.artifactsBusinessLogic - .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, - shouldLock, inTransaction); + .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, shouldLock, inTransaction); if (handleDelete.isRight()) { result = Either.right(handleDelete.right().value()); } return result; } if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) { - operation = new ArtifactOperationInfo(false, false, - ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE); + operation = new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE); } } if (artifactFileBytes != null) { Map vendorLicenseModelJson = ArtifactUtils - .buildJsonForUpdateArtifact(artifactId, artifactFileName, - artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, - artifactFileBytes, null, isFromCsar); + .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, + artifactDescription, artifactFileBytes, null, isFromCsar); Either, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic - .createOrUpdateCsarArtifactFromJson( - component, csarInfo.getModifier(), vendorLicenseModelJson, operation); - serviceImportParseLogic - .addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); + .createOrUpdateCsarArtifactFromJson(component, csarInfo.getModifier(), vendorLicenseModelJson, operation); + serviceImportParseLogic.addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); if (eitherNonMetaArtifacts.isRight()) { - BeEcompErrorManager.getInstance() - .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " - + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), - BeEcompErrorManager.ErrorSeverity.WARNING); + BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", + "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), + BeEcompErrorManager.ErrorSeverity.WARNING); return Either.right(eitherNonMetaArtifacts.right().value()); } } @@ -655,7 +590,6 @@ public class ServiceImportBusinessLogic { 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 (Map.Entry> curOperationEntry : nodeTypeArtifactsToHandle @@ -663,13 +597,10 @@ public class ServiceImportBusinessLogic { ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey(); List curArtifactsToHandle = curOperationEntry.getValue(); if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { - log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), - nodeTypeResource.getName()); + log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName()); handleNodeTypeArtifactsRequestRes = serviceBusinessLogic.artifactsBusinessLogic - .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, - createdArtifacts, new ArtifactOperationInfo(false, - ignoreLifecycleState, curOperation), - false, inTransaction); + .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts, + new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction); if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) { createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes); } @@ -692,11 +623,10 @@ public class ServiceImportBusinessLogic { try { if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState() .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - Either checkoutRes = lifecycleBusinessLogic.changeComponentState( - resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, - new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, - LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), - inTransaction, true); + Either checkoutRes = lifecycleBusinessLogic + .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, + LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true); if (checkoutRes.isRight()) { checkoutResourceRes = Either.right(checkoutRes.right().value()); } else { @@ -708,32 +638,27 @@ public class ServiceImportBusinessLogic { } 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); + log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e); } return checkoutResourceRes; } - protected Either createOrUpdateArtifacts( - ArtifactOperationEnum operation, List createdArtifacts, - String yamlFileName, CsarInfo csarInfo, Service preparedService, - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { - + protected Either createOrUpdateArtifacts(ArtifactOperationEnum operation, List createdArtifacts, + String yamlFileName, CsarInfo csarInfo, Service preparedService, + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, + boolean inTransaction, boolean shouldLock) { Either createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts, new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction); log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); if (createdCsarArtifactsEither.isRight()) { return createdCsarArtifactsEither; } - return Either.left(createdCsarArtifactsEither.left().value()); } - protected Either handleVfCsarArtifacts(Service service, CsarInfo csarInfo, - List createdArtifacts, + protected Either handleVfCsarArtifacts(Service service, CsarInfo csarInfo, List createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, boolean inTransaction) { - if (csarInfo.getCsar() != null) { String vendorLicenseModelId = null; String vfLicenseModelId = null; @@ -750,34 +675,29 @@ public class ServiceImportBusinessLogic { } } } - createOrUpdateSingleNonMetaArtifact(service, 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, true, shouldLock, - inTransaction); - createOrUpdateSingleNonMetaArtifact(service, 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, + createOrUpdateSingleNonMetaArtifact(service, 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, true, shouldLock, inTransaction); - - Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, - createdArtifacts, shouldLock, inTransaction, artifactOperation); + createOrUpdateSingleNonMetaArtifact(service, 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, true, shouldLock, + inTransaction); + Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, createdArtifacts, shouldLock, + inTransaction, artifactOperation); if (eitherCreateResult.isRight()) { return Either.right(eitherCreateResult.right().value()); } - Either eitherGerResource = toscaOperationFacade - .getToscaElement(service.getUniqueId()); + Either eitherGerResource = toscaOperationFacade.getToscaElement(service.getUniqueId()); if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service, ComponentTypeEnum.SERVICE); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service, + ComponentTypeEnum.SERVICE); return Either.right(responseFormat); } service = 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(); @@ -810,8 +730,7 @@ public class ServiceImportBusinessLogic { protected Either createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource, List createdArtifacts, boolean shouldLock, - boolean inTransaction, - ArtifactOperationInfo artifactOperation) { + boolean inTransaction, ArtifactOperationInfo artifactOperation) { return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation); } @@ -825,7 +744,6 @@ public class ServiceImportBusinessLogic { existingArtifacts.addAll(component.getArtifacts().values()); } existingArtifacts = existingArtifacts.stream().filter(this::isNonMetaArtifact).collect(toList()); - List artifactsToIgnore = new ArrayList<>(); if (component.getGroups() != null) { component.getGroups().forEach(g -> { @@ -834,8 +752,7 @@ public class ServiceImportBusinessLogic { } }); } - existingArtifacts = existingArtifacts.stream() - .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList()); + existingArtifacts = existingArtifacts.stream().filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList()); return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, component, user); } @@ -849,8 +766,7 @@ public class ServiceImportBusinessLogic { private boolean isValidArtifactType(ArtifactDefinition artifact) { boolean result = true; - if (artifact.getArtifactType() == null - || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE) + if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE) || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VF_LICENSE)) { result = false; } @@ -858,8 +774,8 @@ public class ServiceImportBusinessLogic { } protected Either>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation( - List artifactPathAndNameList, List existingArtifactsToHandle, - Component component, User user) { + List artifactPathAndNameList, List existingArtifactsToHandle, Component component, + User user) { EnumMap> nodeTypeArtifactsToHandle = new EnumMap<>( ArtifactsBusinessLogic.ArtifactOperationEnum.class); Wrapper responseWrapper = new Wrapper<>(); @@ -871,14 +787,11 @@ public class ServiceImportBusinessLogic { List artifactsToDelete = new ArrayList<>(); for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) { ArtifactDefinition foundArtifact; - if (!existingArtifactsToHandle.isEmpty()) { - foundArtifact = existingArtifactsToHandle.stream() - .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst() - .orElse(null); + foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())) + .findFirst().orElse(null); if (foundArtifact != null) { - if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact - .getArtifactType())) { + if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact.getArtifactType())) { if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); artifactsToUpdate.add(currNewArtifact); @@ -886,18 +799,16 @@ public class ServiceImportBusinessLogic { existingArtifactsToHandle.remove(foundArtifact); artifactsToUpload.remove(currNewArtifact); } else { - log.debug("Can't upload two artifact with the same name {}.", - currNewArtifact.getArtifactName()); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat( - ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, - currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), - foundArtifact.getArtifactType()); + log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), + currNewArtifact.getArtifactType(), foundArtifact.getArtifactType()); AuditingActionEnum auditingAction = serviceBusinessLogic.artifactsBusinessLogic - .detectAuditingType(new ArtifactOperationInfo(false, false, - ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum()); - serviceBusinessLogic.artifactsBusinessLogic.handleAuditing(auditingAction, component, component.getUniqueId(), - user, null, null, foundArtifact.getUniqueId(), responseFormat, - component.getComponentType(), null); + .detectAuditingType(new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE), + foundArtifact.getArtifactChecksum()); + serviceBusinessLogic.artifactsBusinessLogic + .handleAuditing(auditingAction, component, component.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), + responseFormat, component.getComponentType(), null); responseWrapper.setInnerElement(responseFormat); break; } @@ -940,7 +851,6 @@ public class ServiceImportBusinessLogic { return nodeTypeArtifactsToHandleRes; } - public ComponentsUtils getComponentsUtils() { return this.componentsUtils; } @@ -951,15 +861,10 @@ public class ServiceImportBusinessLogic { protected Either, String> getValidArtifactNames(CsarInfo csarInfo, Map>> collectedWarningMessages) { - List artifactPathAndNameList = - csarInfo.getCsar().entrySet().stream() - .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()) - .matches()) - .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), - collectedWarningMessages)) - .filter(Either::isLeft) - .map(e -> e.left().value()) - .collect(toList()); + List artifactPathAndNameList = csarInfo.getCsar().entrySet().stream() + .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) + .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)).filter(Either::isLeft) + .map(e -> e.left().value()).collect(toList()); Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME); for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) { if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) { @@ -969,25 +874,24 @@ public class ServiceImportBusinessLogic { return Either.left(artifactPathAndNameList); } - protected Either createGroupsOnResource(Service service, - Map groups) { + protected Either createGroupsOnResource(Service service, Map groups) { if (groups != null && !groups.isEmpty()) { List groupsAsList = updateGroupsMembersUsingResource(groups, service); serviceImportParseLogic.handleGroupsProperties(service, groups); serviceImportParseLogic.fillGroupsFinalFields(groupsAsList); - Either, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(service, - groupsAsList, true); + Either, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic + .createGroups(service, groupsAsList, true); if (createGroups.isRight()) { return Either.right(createGroups.right().value()); } } else { return Either.left(service); } - Either updatedResource = toscaOperationFacade - .getToscaElement(service.getUniqueId()); + Either updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId()); if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, + ComponentTypeEnum.SERVICE); return Either.right(responseFormat); } return Either.left(updatedResource.left().value()); @@ -1008,8 +912,7 @@ public class ServiceImportBusinessLogic { updatedGroupDefinition.setMembers(null); Map members = groupDefinition.getMembers(); if (members != null) { - serviceImportParseLogic - .updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members); + serviceImportParseLogic.updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members); } result.add(updatedGroupDefinition); } @@ -1017,7 +920,6 @@ public class ServiceImportBusinessLogic { return result; } - protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource, Map uploadComponentInstanceInfoMap, String topologyTemplateYaml, List nodeTypesNewCreatedArtifacts, @@ -1026,11 +928,10 @@ public class ServiceImportBusinessLogic { String nodeName) { try { log.debug("************* Going to create all nodes {}", yamlName); - handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeName); + handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, + csarInfo, nodeName); log.debug("************* Going to create all resource instances {}", yamlName); - resource = createResourceInstances(yamlName, resource, - uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes()); + resource = createResourceInstances(yamlName, resource, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes()); log.debug("************* Finished to create all resource instances {}", yamlName); resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap); log.debug("************* Going to create positions {}", yamlName); @@ -1043,64 +944,61 @@ public class ServiceImportBusinessLogic { } protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, - Map uploadResInstancesMap) { - log.debug("#createResourceInstancesRelations - Going to create relations "); - - List componentInstancesList = resource.getComponentInstances(); - if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) && - resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances - log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName); - BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", BeEcompErrorManager.ErrorSeverity.ERROR); - throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName)); - } - Map> instProperties = new HashMap<>(); - Map>> instCapabilities = 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<>(); - - log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. "); - if(serviceBusinessLogic.dataTypeCache!=null){ - Either, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - JanusGraphOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", - "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); - throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName)); - } - Resource finalResource = resource; - uploadResInstancesMap - .values() - .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, - instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, - instArtifacts, instAttributes, originCompMap, instInputs, i)); - } - serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties); - serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs); - serviceImportParseLogic - .associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); - serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts); - serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); - serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); - resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource); - - serviceImportParseLogic - .addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations); - serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations); - handleSubstitutionMappings(resource, uploadResInstancesMap); - log.debug("************* in create relations, getResource start"); - Either eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - log.debug("************* in create relations, getResource end"); - if (eitherGetResource.isRight()) { - throw new ComponentException(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource)); - } - return eitherGetResource.left().value(); + Map uploadResInstancesMap) { + log.debug("#createResourceInstancesRelations - Going to create relations "); + List componentInstancesList = resource.getComponentInstances(); + if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) && + resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances + log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", + resource.getUniqueId(), yamlName); + BeEcompErrorManager.getInstance() + .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", + BeEcompErrorManager.ErrorSeverity.ERROR); + throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName)); + } + Map> instProperties = new HashMap<>(); + Map>> instCapabilities = 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<>(); + log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. "); + if (serviceBusinessLogic.dataTypeCache != null) { + Either, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + JanusGraphOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", + "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); + throw new ComponentException(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), + yamlName)); + } + Resource finalResource = resource; + uploadResInstancesMap.values().forEach( + i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities, + instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, i)); + } + serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties); + serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs); + serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); + serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts); + serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); + serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); + resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource); + serviceImportParseLogic.addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations); + serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations); + handleSubstitutionMappings(resource, uploadResInstancesMap); + log.debug("************* in create relations, getResource start"); + Either eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); + log.debug("************* in create relations, getResource end"); + if (eitherGetResource.isRight()) { + throw new ComponentException( + componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource)); + } + return eitherGetResource.left().value(); } protected void processProperty(Resource resource, ComponentInstance currentCompInstance, Map allDataTypes, @@ -1109,8 +1007,7 @@ public class ServiceImportBusinessLogic { UploadPropInfo propertyInfo = propertyList.get(0); String propName = propertyInfo.getName(); if (!currPropertiesMap.containsKey(propName)) { - throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - propName)); + throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName)); } processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, resource.getInputs()); } @@ -1120,7 +1017,6 @@ public class ServiceImportBusinessLogic { List inputs2) { InputDefinition curPropertyDef = currPropertiesMap.get(propName); ComponentInstanceInput property = null; - String value = null; List getInputs = null; boolean isValidate = true; @@ -1128,17 +1024,14 @@ public class ServiceImportBusinessLogic { getInputs = propertyInfo.getGet_input(); isValidate = getInputs == null || getInputs.isEmpty(); if (isValidate) { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - curPropertyDef.getType()); + value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); } } property = new ComponentInstanceInput(curPropertyDef, value, null); String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); property.setValue(validPropertyVAlue); - if (isNotEmpty(getInputs)) { List getInputValues = new ArrayList<>(); for (GetInputValueDataDefinition getInput : getInputs) { @@ -1146,16 +1039,13 @@ public class ServiceImportBusinessLogic { if (CollectionUtils.isEmpty(inputs)) { throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } - - Optional optional = inputs.stream() - .filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + Optional optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny(); if (!optional.isPresent()) { throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } InputDefinition input = optional.get(); getInput.setInputId(input.getUniqueId()); getInputValues.add(getInput); - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); processGetInput(getInputValues, inputs, getInputIndex); } @@ -1169,22 +1059,20 @@ public class ServiceImportBusinessLogic { if (resource.getResourceType() == ResourceTypeEnum.VF) { Either getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId()); if (getResourceRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); throw new ComponentException(responseFormat); } - getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), - uploadResInstancesMap); + getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap); if (getResourceRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); throw new ComponentException(responseFormat); } } } - protected Resource createResourceInstances(String yamlName, Resource resource, - Map uploadResInstancesMap, + protected Resource createResourceInstances(String yamlName, Resource resource, Map uploadResInstancesMap, Map nodeNamespaceMap) { Either eitherResource = null; log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); @@ -1197,14 +1085,11 @@ public class ServiceImportBusinessLogic { nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v)); } Map resourcesInstancesMap = new HashMap<>(); - uploadResInstancesMap - .values() + uploadResInstancesMap.values() .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap)); - if (MapUtils.isNotEmpty(resourcesInstancesMap)) { try { - toscaOperationFacade.associateComponentInstancesToComponent(resource, - resourcesInstancesMap, false, false); + toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, false); } catch (StorageException exp) { if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) { log.debug("Failed to add component instances to container component {}", resource.getName()); @@ -1220,37 +1105,34 @@ public class ServiceImportBusinessLogic { .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter()); log.debug("*************finished to get resource {}", resource.getUniqueId()); if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); throw new ComponentException(responseFormat); } if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances log.debug("Error when create resource instance from csar. ComponentInstances list empty"); - BeEcompErrorManager.getInstance().logBeDaoSystemError( - "Error when create resource instance from csar. ComponentInstances list empty"); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty"); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); } return eitherGetResource.left().value(); } - protected void handleNodeTypes(String yamlName, Resource resource, - String topologyTemplateYaml, boolean needLock, + protected void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock, Map>> nodeTypesArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, - CsarInfo csarInfo, String nodeName) { + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, CsarInfo csarInfo, + String nodeName) { try { for (Map.Entry nodeTypeEntry : nodeTypesInfo.entrySet()) { if (nodeTypeEntry.getValue().isNested()) { - - handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); + handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypeEntry.getKey()); log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); } } Map mappedToscaTemplate = null; - if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) - && nodeTypesInfo.containsKey(nodeName)) { + if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo + .containsKey(nodeName)) { mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); } if (MapUtils.isEmpty(mappedToscaTemplate)) { @@ -1259,8 +1141,8 @@ public class ServiceImportBusinessLogic { createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); } catch (ComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() - : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); + ResponseFormat responseFormat = + e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); throw e; } catch (StorageException e) { @@ -1281,8 +1163,8 @@ public class ServiceImportBusinessLogic { try { String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); - createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, - nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); + createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, + csarInfo); log.debug("************* Finished to create node types from yaml {}", yamlName); if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { log.debug("************* Going to handle complex VFC from yaml {}", yamlName); @@ -1301,15 +1183,12 @@ public class ServiceImportBusinessLogic { String nodeName) { String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); - log.debug("************* Going to create node types from yaml {}", yamlName); - createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, - nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); - + createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, + csarInfo); if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { log.debug("************* Going to handle complex VFC from yaml {}", yamlName); - resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, - csarInfo, nodeName, yamlName); + resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName); } return resource; } @@ -1324,29 +1203,27 @@ public class ServiceImportBusinessLogic { .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName( - serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), - nodeName).getRight()); + serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getRight()); } if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { throw new ComponentException(ActionStatus.GENERAL_ERROR); } else if (oldComplexVfcRes.isLeft()) { log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); - Either eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate( - oldComplexVfcRes.left().value(), newComplexVfc, - ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); + Either eitherValidation = serviceImportParseLogic + .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc, + ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); if (eitherValidation.isLeft()) { oldComplexVfc = oldComplexVfcRes.left().value(); } } - newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, - oldComplexVfc, newComplexVfc); + newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, + newComplexVfc); csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction( - CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, + LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); final Resource result = serviceImportParseLogic - .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, - true); + .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true); csarInfo.getCreatedNodes().put(nodeName, result); csarInfo.removeNodeFromQueue(); return result; @@ -1356,8 +1233,7 @@ public class ServiceImportBusinessLogic { boolean needLock, Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts, - Map nodeTypesInfo, - CsarInfo csarInfo) { + Map nodeTypesInfo, CsarInfo csarInfo) { Either toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); if (toscaVersion.isRight()) { @@ -1379,28 +1255,21 @@ public class ServiceImportBusinessLogic { Resource vfcCreated = null; while (nodesNameValueIter.hasNext()) { Map.Entry nodeType = nodesNameValueIter.next(); - Map> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null - || nodeTypesArtifactsToHandle.isEmpty() ? null - : nodeTypesArtifactsToHandle.get(nodeType.getKey()); - + 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()); - vfcCreated = handleNestedVfc(resource, - nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeType.getKey()); log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); - } else if (csarInfo.getCreatedNodesToscaResourceNames() != null - && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { + } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames() + .containsKey(nodeType.getKey())) { log.trace("************* Going to create node {}", nodeType.getKey()); ImmutablePair resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), - mapToConvert, - resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, - csarInfo, true); + mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true); log.debug("************* Finished to create node {}", nodeType.getKey()); - vfcCreated = resourceCreated.getLeft(); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), - vfcCreated.getToscaResourceName()); + csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName()); } if (vfcCreated != null) { csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); @@ -1409,21 +1278,18 @@ public class ServiceImportBusinessLogic { } } - protected ImmutablePair createNodeTypeResourceFromYaml( - String yamlName, Map.Entry nodeNameValue, User user, Map mapToConvert, - Resource resourceVf, boolean needLock, - Map> nodeTypeArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, - boolean isNested) { - UploadResourceInfo resourceMetaData = serviceImportParseLogic - .fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); - - String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, - resourceMetaData.getResourceType(), csarInfo); + protected ImmutablePair createNodeTypeResourceFromYaml(String yamlName, Map.Entry nodeNameValue, + User user, Map mapToConvert, Resource resourceVf, + boolean needLock, + Map> nodeTypeArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, + boolean forceCertificationAllowed, CsarInfo csarInfo, + boolean isNested) { + UploadResourceInfo resourceMetaData = serviceImportParseLogic.fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); + String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo); user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); - return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, - nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, - nodeNameValue.getKey(), isNested); + return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle, + nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested); } protected Service createRIAndRelationsFromYaml(String yamlName, Service service, @@ -1447,110 +1313,97 @@ public class ServiceImportBusinessLogic { protected Service createServiceInstancesRelations(User user, String yamlName, Service service, Map uploadResInstancesMap) { - - log.debug("#createResourceInstancesRelations - Going to create relations "); - List componentInstancesList = service.getComponentInstances(); - if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances - log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", + log.debug("#createResourceInstancesRelations - Going to create relations "); + List componentInstancesList = service.getComponentInstances(); + if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances + log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", service.getUniqueId(), yamlName); - BeEcompErrorManager.getInstance() + BeEcompErrorManager.getInstance() .logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ", BeEcompErrorManager.ErrorSeverity.ERROR); - throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName)); - } - Map> instProperties = new HashMap<>(); - Map>> instCapabilities = 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<>(); - - log.debug("enter ServiceImportBusinessLogic createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. "); - if(serviceBusinessLogic.dataTypeCache!=null){ - Either, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - JanusGraphOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", - "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); - throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName)); - } - Service finalResource = service; - uploadResInstancesMap - .values() - .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, - instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, - instArtifacts, instAttributes, originCompMap, instInputs, i)); - - } - serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties); - serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs); - serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts); - serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts); - serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements); - log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", - instRequirements, instCapabilities); - serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes); - ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service); - Map capabilities = serviceTemplate.getCapabilities(); - Map requirements = serviceTemplate.getRequirements(); - - serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities); - serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements); - service = getResourceAfterCreateRelations(service); - - addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations); - serviceImportParseLogic.associateResourceInstances(yamlName, service, relations); - handleSubstitutionMappings(service, uploadResInstancesMap); - log.debug("************* in create relations, getResource start"); - Either eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId()); - log.debug("************* in create relations, getResource end"); - if (eitherGetResource.isRight()) { - throw new ComponentException(componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, service.getComponentType())); - } - return eitherGetResource.left().value(); - } - - protected void processComponentInstance(String yamlName, Component component, - List componentInstancesList, + throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName)); + } + Map> instProperties = new HashMap<>(); + Map>> instCapabilities = 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<>(); + log.debug("enter ServiceImportBusinessLogic createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. "); + if (serviceBusinessLogic.dataTypeCache != null) { + Either, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + JanusGraphOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", + "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); + throw new ComponentException(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), + yamlName)); + } + Service finalResource = service; + uploadResInstancesMap.values().forEach( + i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities, + instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, i)); + } + serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties); + serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs); + serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts); + serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts); + serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements); + log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", instRequirements, instCapabilities); + serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes); + ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service); + Map capabilities = serviceTemplate.getCapabilities(); + Map requirements = serviceTemplate.getRequirements(); + serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities); + serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements); + service = getResourceAfterCreateRelations(service); + addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations); + serviceImportParseLogic.associateResourceInstances(yamlName, service, relations); + handleSubstitutionMappings(service, uploadResInstancesMap); + log.debug("************* in create relations, getResource start"); + Either eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId()); + log.debug("************* in create relations, getResource end"); + if (eitherGetResource.isRight()) { + throw new ComponentException(componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, + service.getComponentType())); + } + return eitherGetResource.left().value(); + } + + protected void processComponentInstance(String yamlName, Component component, List componentInstancesList, Either, JanusGraphOperationStatus> allDataTypes, Map> instProperties, Map>> instCapabilties, Map>> instRequirements, Map> instDeploymentArtifacts, Map> instArtifacts, - Map> instAttributes, - Map originCompMap, + Map> instAttributes, Map originCompMap, Map> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) { log.debug("enter ServiceImportBusinessLogic processComponentInstance"); Optional currentCompInstanceOpt = componentInstancesList.stream() - .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())) - .findFirst(); + .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst(); if (!currentCompInstanceOpt.isPresent()) { - log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), - component.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, - component.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), component.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, component.getUniqueId(), + BeEcompErrorManager.ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); throw new ComponentException(responseFormat); } ComponentInstance currentCompInstance = currentCompInstanceOpt.get(); String resourceInstanceId = currentCompInstance.getUniqueId(); Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance); - if (MapUtils.isNotEmpty(originResource.getRequirements())) { instRequirements.put(currentCompInstance, originResource.getRequirements()); } if (MapUtils.isNotEmpty(originResource.getCapabilities())) { - processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, - currentCompInstance, originResource); + processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource); } if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) { instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); @@ -1562,27 +1415,24 @@ public class ServiceImportBusinessLogic { instAttributes.put(resourceInstanceId, originResource.getAttributes()); } if (originResource.getResourceType() != ResourceTypeEnum.VF) { - ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, - originResource, currentCompInstance, instProperties, allDataTypes.left().value()); + ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, originResource, + currentCompInstance, instProperties, allDataTypes.left().value()); if (addPropertiesValueToRiRes.getStatus() != 200) { throw new ComponentException(addPropertiesValueToRiRes); } } else { - addInputsValuesToRi(uploadComponentInstanceInfo, component, - originResource, currentCompInstance, instInputs, allDataTypes.left().value()); + addInputsValuesToRi(uploadComponentInstanceInfo, component, originResource, currentCompInstance, instInputs, allDataTypes.left().value()); } } - - protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, - Component component, Resource originResource, ComponentInstance currentCompInstance, - Map> instInputs, Map allDataTypes) { + protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, Resource originResource, + ComponentInstance currentCompInstance, Map> instInputs, + Map allDataTypes) { Map> propMap = uploadComponentInstanceInfo.getProperties(); try { if (MapUtils.isNotEmpty(propMap)) { Map currPropertiesMap = new HashMap<>(); List instPropList = new ArrayList<>(); - if (CollectionUtils.isEmpty(originResource.getInputs())) { log.debug("failed to find properties "); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); @@ -1607,8 +1457,7 @@ public class ServiceImportBusinessLogic { String propName = propertyInfo.getName(); if (!currPropertiesMap.containsKey(propName)) { log.debug("failed to find property {} ", propName); - throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - propName)); + throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName)); } processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs()); } @@ -1617,8 +1466,7 @@ public class ServiceImportBusinessLogic { GetInputValueDataDefinition getInputIndex) { Optional optional; if (getInputIndex != null) { - optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())) - .findAny(); + optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny(); if (!optional.isPresent()) { log.debug("Failed to find input {} ", getInputIndex.getInputName()); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); @@ -1629,13 +1477,12 @@ public class ServiceImportBusinessLogic { } } - protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, - Component component, Resource originResource, ComponentInstance currentCompInstance, + protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, + Resource originResource, ComponentInstance currentCompInstance, 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 "); @@ -1657,12 +1504,10 @@ public class ServiceImportBusinessLogic { String propName = propertyInfo.getName(); if (!currPropertiesMap.containsKey(propName)) { log.debug("failed to find property {} ", propName); - return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - propName); + return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); } PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); ComponentInstanceProperty property = null; - String value = null; List getInputs = null; boolean isValidate = true; @@ -1670,33 +1515,26 @@ public class ServiceImportBusinessLogic { getInputs = propertyInfo.getGet_input(); isValidate = getInputs == null || getInputs.isEmpty(); if (isValidate) { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - curPropertyDef.getType()); + value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); } } property = new ComponentInstanceProperty(curPropertyDef, value, null); - String validatePropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes); property.setValue(validatePropValue); - if (getInputs != null && !getInputs.isEmpty()) { List getInputValues = new ArrayList<>(); for (GetInputValueDataDefinition getInput : getInputs) { List inputs = component.getInputs(); if (inputs == null || inputs.isEmpty()) { log.debug("Failed to add property {} to instance. Inputs list is empty ", property); - serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() - .stream() - .map(GetInputValueDataDefinition::getInputName) - .collect(toList()).toString()); + serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, + property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString()); } InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput); getInput.setInputId(input.getUniqueId()); getInputValues.add(getInput); - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); if (getInputIndex != null) { input = serviceImportParseLogic.findInputByName(inputs, getInputIndex); @@ -1728,10 +1566,9 @@ public class ServiceImportBusinessLogic { if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { originCapabilities = new HashMap<>(); Map> newPropertiesMap = new HashMap<>(); - originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic - .addCapabilities(originCapabilities, k, v)); - uploadComponentInstanceInfo.getCapabilities().values().forEach(l -> serviceImportParseLogic - .addCapabilitiesProperties(newPropertiesMap, l)); + originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic.addCapabilities(originCapabilities, k, v)); + uploadComponentInstanceInfo.getCapabilities().values() + .forEach(l -> serviceImportParseLogic.addCapabilitiesProperties(newPropertiesMap, l)); updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap); } else { originCapabilities = originResource.getCapabilities(); @@ -1742,9 +1579,7 @@ public class ServiceImportBusinessLogic { protected void updateCapabilityPropertiesValues(Either, JanusGraphOperationStatus> allDataTypes, Map> originCapabilities, Map> newPropertiesMap) { - originCapabilities.values().stream() - .flatMap(Collection::stream) - .filter(c -> newPropertiesMap.containsKey(c.getName())) + originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName())) .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value())); } @@ -1764,8 +1599,7 @@ public class ServiceImportBusinessLogic { if (isValidate) { value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); } else { - value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); } } property.setValue(value); @@ -1779,8 +1613,8 @@ public class ServiceImportBusinessLogic { Either getOriginResourceRes = toscaOperationFacade .getToscaFullElement(currentCompInstance.getComponentUid()); if (getOriginResourceRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); throw new ComponentException(responseFormat); } originResource = getOriginResourceRes.left().value(); @@ -1795,15 +1629,16 @@ public class ServiceImportBusinessLogic { if (false) { Either getResourceRes = toscaOperationFacade.getToscaFullElement(service.getUniqueId()); if (getResourceRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, + ComponentTypeEnum.SERVICE); throw new ComponentException(responseFormat); } - getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), - uploadResInstancesMap); + getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap); if (getResourceRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, + ComponentTypeEnum.SERVICE); throw new ComponentException(responseFormat); } } @@ -1814,19 +1649,16 @@ public class ServiceImportBusinessLogic { Either updateRes = null; Map>> updatedInstCapabilities = new HashMap<>(); Map>> updatedInstRequirements = new HashMap<>(); - StorageOperationStatus status = toscaOperationFacade - .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId()); + 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 {}", + 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.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, - resource); + fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities, + updatedInstRequirements); + status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource); if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { updateRes = Either.right(status); } @@ -1842,30 +1674,25 @@ public class ServiceImportBusinessLogic { Map>> updatedInstCapabilities, Map>> updatedInstRequirements) { componentInstances.stream().forEach(i -> { - fillUpdatedInstCapabilities(updatedInstCapabilities, i, - uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); - fillUpdatedInstRequirements(updatedInstRequirements, i, - uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); + fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); + fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); }); } - protected void fillUpdatedInstCapabilities( - Map>> updatedInstCapabilties, - ComponentInstance instance, Map capabilitiesNamesToUpdate) { + protected 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(toList())); + 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(toList())); } } if (MapUtils.isNotEmpty(updatedCapabilities)) { @@ -1873,23 +1700,20 @@ public class ServiceImportBusinessLogic { } } - protected void fillUpdatedInstRequirements( - Map>> updatedInstRequirements, - ComponentInstance instance, Map requirementsNamesToUpdate) { + protected 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(toList())); + 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(toList())); } } if (MapUtils.isNotEmpty(updatedRequirements)) { @@ -1909,16 +1733,13 @@ public class ServiceImportBusinessLogic { } } if (currentCompInstance == null) { - log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), - service.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, - service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), service.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, service.getUniqueId(), + BeEcompErrorManager.ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); throw new ComponentException(responseFormat); } - ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations); if (addRelationToRiRes.getStatus() != 200) { throw new ComponentException(addRelationToRiRes); @@ -1926,8 +1747,8 @@ public class ServiceImportBusinessLogic { } } - protected ResponseFormat addRelationToRI(String yamlName, Service service, - UploadComponentInstanceInfo nodesInfoValue, List relations) { + protected ResponseFormat addRelationToRI(String yamlName, Service service, UploadComponentInstanceInfo nodesInfoValue, + List relations) { List componentInstancesList = service.getComponentInstances(); ComponentInstance currentCompInstance = null; for (ComponentInstance compInstance : componentInstancesList) { @@ -1937,17 +1758,14 @@ public class ServiceImportBusinessLogic { } } if (currentCompInstance == null) { - log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), - service.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, - service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); - return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, - yamlName); + log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), service.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, service.getUniqueId(), + BeEcompErrorManager.ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } String resourceInstanceId = currentCompInstance.getUniqueId(); Map> regMap = nodesInfoValue.getRequirements(); - if (regMap != null) { Iterator>> nodesRegValue = regMap.entrySet().iterator(); while (nodesRegValue.hasNext()) { @@ -1959,18 +1777,14 @@ public class ServiceImportBusinessLogic { RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); regCapRelDef.setFromNode(resourceInstanceId); log.debug("try to find available requirement {} ", regName); - Either eitherReqStatus = serviceImportParseLogic.findAviableRequiremen(regName, - yamlName, nodesInfoValue, currentCompInstance, - uploadRegInfo.getCapabilityName()); + Either eitherReqStatus = serviceImportParseLogic + .findAviableRequiremen(regName, yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName()); if (eitherReqStatus.isRight()) { - log.debug("failed to find available requirement {} status is {}", regName, - eitherReqStatus.right().value()); + 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(); + List reqAndRelationshipPairList = regCapRelDef.getRelationships(); if (reqAndRelationshipPairList == null) { reqAndRelationshipPairList = new ArrayList<>(); } @@ -1981,7 +1795,6 @@ public class ServiceImportBusinessLogic { RelationshipImpl relationship = new RelationshipImpl(); relationship.setType(validReq.getCapability()); reqAndRelationshipPair.setRelationships(relationship); - ComponentInstance currentCapCompInstance = null; for (ComponentInstance compInstance : componentInstancesList) { if (compInstance.getName().equals(uploadRegInfo.getNode())) { @@ -1990,28 +1803,24 @@ public class ServiceImportBusinessLogic { } } if (currentCapCompInstance == null) { - log.debug("The component instance with name {} not found on resource {} ", - uploadRegInfo.getNode(), service.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, - service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); - return componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), service.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, service.getUniqueId(), + BeEcompErrorManager.ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); log.debug("try to find aviable Capability req name is {} ", validReq.getName()); - CapabilityDefinition aviableCapForRel = serviceImportParseLogic.findAvailableCapabilityByTypeOrName(validReq, - currentCapCompInstance, uploadRegInfo); + CapabilityDefinition aviableCapForRel = serviceImportParseLogic + .findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo); reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); if (aviableCapForRel == null) { BeEcompErrorManager.getInstance().logInternalDataError( - "aviable capability was not found. req name is " + validReq.getName() - + " component instance is " + currentCapCompInstance.getUniqueId(), - service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); - return componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance + .getUniqueId(), service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); capReqRel.setRelation(reqAndRelationshipPair); @@ -2026,16 +1835,14 @@ public class ServiceImportBusinessLogic { protected Service getResourceAfterCreateRelations(Service service) { ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations(); - Either eitherGetResource = toscaOperationFacade - .getToscaElement(service.getUniqueId(), parametersView); + Either eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId(), parametersView); if (eitherGetResource.isRight()) { serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service); } return eitherGetResource.left().value(); } - protected Service createServiceInstances(String yamlName, Service service, - Map uploadResInstancesMap, + protected Service createServiceInstances(String yamlName, Service service, Map uploadResInstancesMap, Map nodeNamespaceMap) { Either eitherResource = null; log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); @@ -2048,14 +1855,11 @@ public class ServiceImportBusinessLogic { nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v)); } Map resourcesInstancesMap = new HashMap<>(); - uploadResInstancesMap - .values() + uploadResInstancesMap.values() .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap)); - if (MapUtils.isNotEmpty(resourcesInstancesMap)) { try { - toscaOperationFacade.associateComponentInstancesToComponent(service, - resourcesInstancesMap, false, false); + toscaOperationFacade.associateComponentInstancesToComponent(service, resourcesInstancesMap, false, false); } catch (StorageException exp) { if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) { log.debug("Failed to add component instances to container component {}", service.getName()); @@ -2070,31 +1874,28 @@ public class ServiceImportBusinessLogic { .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter()); log.debug("*************finished to get resource {}", service.getUniqueId()); if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, ComponentTypeEnum.SERVICE); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, + ComponentTypeEnum.SERVICE); throw new ComponentException(responseFormat); } if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances log.debug("Error when create resource instance from csar. ComponentInstances list empty"); - BeEcompErrorManager.getInstance().logBeDaoSystemError( - "Error when create resource instance from csar. ComponentInstances list empty"); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty"); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); } return eitherGetResource.left().value(); } - protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, - Component component, Map nodeNamespaceMap, - Map existingnodeTypeMap, Map resourcesInstancesMap) { + protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Component component, + Map nodeNamespaceMap, Map existingnodeTypeMap, + Map resourcesInstancesMap) { log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); try { if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { - uploadComponentInstanceInfo - .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); + uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); } - Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, - existingnodeTypeMap); - + Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap); ComponentInstance componentInstance = new ComponentInstance(); componentInstance.setComponentUid(refResource.getUniqueId()); Collection directives = uploadComponentInstanceInfo.getDirectives(); @@ -2103,25 +1904,23 @@ public class ServiceImportBusinessLogic { } UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo(); if (uploadNodeFilterInfo != null) { - componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, - componentInstance.getUniqueId())); + componentInstance + .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId())); } - ComponentTypeEnum containerComponentType = component.getComponentType(); NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); - if (containerNodeType.equals(NodeTypeEnum.Resource) - && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) - && MapUtils.isNotEmpty(refResource.getCapabilities())) { + if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils + .isNotEmpty(refResource.getCapabilities())) { serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); Map> validComponentInstanceCapabilities = serviceImportParseLogic - .getValidComponentInstanceCapabilities( - refResource.getUniqueId(), refResource.getCapabilities(), + .getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); componentInstance.setCapabilities(validComponentInstanceCapabilities); } if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), + uploadComponentInstanceInfo.getType()); throw new ComponentException(responseFormat); } Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); @@ -2143,8 +1942,8 @@ public class ServiceImportBusinessLogic { Either findResourceEither = toscaOperationFacade .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType()); if (findResourceEither.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); throw new ComponentException(responseFormat); } refResource = findResourceEither.left().value(); @@ -2152,14 +1951,16 @@ public class ServiceImportBusinessLogic { } String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState(); if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, - refResource.getComponentType().getValue(), refResource.getName(), componentState); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), + componentState); throw new ComponentException(responseFormat); } if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) { log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), + uploadComponentInstanceInfo.getType()); throw new ComponentException(responseFormat); } return refResource; @@ -2168,8 +1969,7 @@ public class ServiceImportBusinessLogic { } } - protected void handleServiceNodeTypes(String yamlName, Service service, - String topologyTemplateYaml, boolean needLock, + protected void handleServiceNodeTypes(String yamlName, Service service, String topologyTemplateYaml, boolean needLock, Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, CsarInfo csarInfo, String nodeName) { @@ -2177,14 +1977,14 @@ public class ServiceImportBusinessLogic { for (Map.Entry nodeTypeEntry : nodeTypesInfo.entrySet()) { boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey()); if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) { - handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); + handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypeEntry.getKey()); log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); } } Map mappedToscaTemplate = null; - if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) - && nodeTypesInfo.containsKey(nodeName)) { + if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo + .containsKey(nodeName)) { mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); } if (MapUtils.isEmpty(mappedToscaTemplate)) { @@ -2217,11 +2017,9 @@ public class ServiceImportBusinessLogic { try { String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); - createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); log.debug("************* Finished to create node types from yaml {}", yamlName); - if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { log.debug("************* Going to handle complex VFC from yaml {}", yamlName); return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName); @@ -2235,8 +2033,7 @@ public class ServiceImportBusinessLogic { protected Resource handleComplexVfc( Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName, String yamlName) { + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) { try { Resource oldComplexVfc = null; Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo); @@ -2244,31 +2041,30 @@ public class ServiceImportBusinessLogic { .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName( - serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), - nodeName).getRight()); + serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.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()); + log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), + oldComplexVfcRes.right().value()); throw new ComponentException(ActionStatus.GENERAL_ERROR); } else if (oldComplexVfcRes.isLeft()) { log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); - Either eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate( - oldComplexVfcRes.left().value(), newComplexVfc, - ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); + Either eitherValidation = serviceImportParseLogic + .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc, + ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); if (eitherValidation.isLeft()) { oldComplexVfc = oldComplexVfcRes.left().value(); } } - newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, - oldComplexVfc, newComplexVfc); + newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, + newComplexVfc); csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction( - CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, + LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); final Resource result = serviceImportParseLogic - .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, - true); + .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true); csarInfo.getCreatedNodes().put(nodeName, result); csarInfo.removeNodeFromQueue(); return result; @@ -2280,8 +2076,8 @@ public class ServiceImportBusinessLogic { protected Resource handleComplexVfc( Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName, + Resource oldComplexVfc, Resource newComplexVfc) { Resource handleComplexVfcRes; try { Map mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate(); @@ -2290,12 +2086,11 @@ public class ServiceImportBusinessLogic { .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy())); CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); if (oldComplexVfc == null) { - handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, - csarInfo, nodesArtifactsToHandle, false, true, nodeName); + handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle, + false, true, nodeName); } else { - handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, - AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo, - newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); + handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, + createdArtifacts, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); } return handleComplexVfcRes; } catch (Exception e) { @@ -2304,9 +2099,9 @@ public class ServiceImportBusinessLogic { } } - protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, - AuditingActionEnum actionEnum, List createdArtifacts, - String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map nodeTypesInfo, + protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum actionEnum, + List createdArtifacts, String yamlFileName, String yamlFileContent, + CsarInfo csarInfo, Map nodeTypesInfo, Map>> nodeTypesArtifactsToHandle, String nodeName, boolean isNested) { boolean inTransaction = true; @@ -2320,14 +2115,13 @@ public class ServiceImportBusinessLogic { if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) { throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName); } - preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), - inTransaction, shouldLock, isNested).left; + preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock, + isNested).left; log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); serviceImportParseLogic.handleResourceGenericType(preparedResource); - handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, - shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName); - preparedResource = serviceImportParseLogic - .createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs()); + handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, + csarInfo, nodeName); + preparedResource = serviceImportParseLogic.createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs()); preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes()); preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances); } catch (ComponentException e) { @@ -2346,8 +2140,7 @@ public class ServiceImportBusinessLogic { throw e; } Either, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic - .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), - preparedResource.getSystemName()); + .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName()); if (validateUpdateVfGroupNamesRes.isRight()) { throw new ComponentException(validateUpdateVfGroupNamesRes.right().value()); } @@ -2359,30 +2152,25 @@ public class ServiceImportBusinessLogic { } serviceImportParseLogic.handleGroupsProperties(preparedResource, groups); preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups); - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, - nodeTypesArtifactsToHandle); - - Either updateArtifactsEither = createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName, - csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle); + Either updateArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, + createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); if (updateArtifactsEither.isRight()) { log.debug("failed to update artifacts {}", updateArtifactsEither.right().value()); throw new ComponentException(updateArtifactsEither.right().value()); } preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId()); - ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource); if (mergingPropsAndInputsStatus != ActionStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, - preparedResource); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource); throw new ComponentException(responseFormat); } compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); return preparedResource; } - protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, - String yamlName, Map nodeTypesInfo, CsarInfo csarInfo, + protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName, + Map nodeTypesInfo, CsarInfo csarInfo, Map>> nodeTypesArtifactsToCreate, boolean shouldLock, boolean inTransaction, String nodeName) { List createdArtifacts = new ArrayList<>(); @@ -2394,9 +2182,8 @@ public class ServiceImportBusinessLogic { throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName()); - createdResource = createResourceAndRIsFromYaml(yamlName, resource, - parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, - nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); + createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, + createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName()); } catch (ComponentException e) { ResponseFormat responseFormat = @@ -2412,16 +2199,15 @@ public class ServiceImportBusinessLogic { return createdResource; } - protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, - ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, - List createdArtifacts, String topologyTemplateYaml, - Map nodeTypesInfo, CsarInfo csarInfo, + protected Resource 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) { List nodeTypesNewCreatedArtifacts = new ArrayList<>(); if (shouldLock) { - Either lockResult = serviceBusinessLogic.lockComponentByName(resource.getSystemName(), resource, - CREATE_RESOURCE); + Either lockResult = serviceBusinessLogic + .lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE); if (lockResult.isRight()) { serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(lockResult.right().value()); @@ -2431,10 +2217,8 @@ public class ServiceImportBusinessLogic { try { log.trace("************* createResourceFromYaml before full create resource {}", yamlName); Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource); - resource = createResourceTransaction(resource, - csarInfo.getModifier(), isNormative); + resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative); log.trace("************* Going to add inputs from yaml {}", yamlName); - Map yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent()); Map metadata = (Map) yamlMap.get("metadata"); String type = (String) metadata.get("type"); @@ -2443,11 +2227,9 @@ public class ServiceImportBusinessLogic { } Map inputs = parsedToscaYamlInfo.getInputs(); resource = serviceImportParseLogic.createInputsOnResource(resource, inputs); - Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo - .getInstances(); - resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, - topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, - nodeTypesArtifactsToCreate, nodeName); + Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances(); + resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml, + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName); log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); // validate update vf module group names Either, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic @@ -2458,32 +2240,25 @@ public class ServiceImportBusinessLogic { } 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, - groups); + Either createGroupsOnResource = createGroupsOnResource(resource, groups); if (createGroupsOnResource.isRight()) { serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(createGroupsOnResource.right().value()); } resource = createGroupsOnResource.left().value(); log.trace("************* Going to add artifacts from yaml {}", yamlName); - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate); - - Either createArtifactsEither = createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, - csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + Either createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, + createdArtifacts, yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); if (createArtifactsEither.isRight()) { serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(createArtifactsEither.right().value()); } - resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum); @@ -2503,26 +2278,23 @@ public class ServiceImportBusinessLogic { } } - protected Either createGroupsOnResource(Resource resource, - Map groups) { + protected Either createGroupsOnResource(Resource resource, Map groups) { if (groups != null && !groups.isEmpty()) { - List groupsAsList = updateGroupsMembersUsingResource( - groups, resource); + List groupsAsList = updateGroupsMembersUsingResource(groups, resource); serviceImportParseLogic.handleGroupsProperties(resource, groups); serviceImportParseLogic.fillGroupsFinalFields(groupsAsList); - Either, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(resource, - groupsAsList, true); + Either, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic + .createGroups(resource, groupsAsList, true); if (createGroups.isRight()) { return Either.right(createGroups.right().value()); } } else { return Either.left(resource); } - Either updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); + Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); return Either.right(responseFormat); } return Either.left(updatedResource.left().value()); @@ -2531,7 +2303,6 @@ public class ServiceImportBusinessLogic { protected List updateGroupsMembersUsingResource(Map groups, Resource component) { List result = new ArrayList<>(); List componentInstances = component.getComponentInstances(); - if (groups != null) { Either validateCyclicGroupsDependencies = serviceImportParseLogic.validateCyclicGroupsDependencies(groups); if (validateCyclicGroupsDependencies.isRight()) { @@ -2557,19 +2328,16 @@ public class ServiceImportBusinessLogic { Set compInstancesNames = members.keySet(); if (CollectionUtils.isEmpty(componentInstances)) { String membersAstString = compInstancesNames.stream().collect(joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", - membersAstString, groupName, component.getNormalizedName()); - throw new ComponentException(componentsUtils.getResponseFormat( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, - component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component))); - } - Map memberNames = componentInstances.stream() - .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, + groupName, component.getNormalizedName()); + throw new ComponentException(componentsUtils + .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), + serviceImportParseLogic.getComponentTypeForResponse(component))); + } + Map memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> ""))); - Map relevantInstances = memberNames.entrySet().stream() - .filter(n -> compInstancesNames.contains(n.getKey())) + Map relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); - if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { List foundMembers = new ArrayList<>(); if (relevantInstances != null) { @@ -2577,17 +2345,16 @@ public class ServiceImportBusinessLogic { } compInstancesNames.removeAll(foundMembers); String membersAstString = compInstancesNames.stream().collect(joining(",")); - throw new ComponentException(componentsUtils.getResponseFormat( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, - component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component))); + throw new ComponentException(componentsUtils + .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), + serviceImportParseLogic.getComponentTypeForResponse(component))); } updatedGroupDefinition.setMembers(relevantInstances); } - protected Resource createResourceTransaction(Resource resource, User user, - boolean isNormative) { - Either eitherValidation = toscaOperationFacade.validateComponentNameExists( - resource.getName(), resource.getResourceType(), resource.getComponentType()); + protected Resource createResourceTransaction(Resource resource, User user, boolean isNormative) { + Either eitherValidation = toscaOperationFacade + .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); if (eitherValidation.isRight()) { ResponseFormat errorResponse = componentsUtils .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); @@ -2595,8 +2362,8 @@ public class ServiceImportBusinessLogic { } 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()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); throw new ComponentException(errorResponse); } log.debug("send resource {} to dao for create", resource.getName()); @@ -2610,38 +2377,31 @@ public class ServiceImportBusinessLogic { resource.setAbstract(false); } } - return toscaOperationFacade.createToscaComponent(resource) - .left() + return toscaOperationFacade.createToscaComponent(resource).left() .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource)); } - protected ImmutablePair updateExistingResourceByImport( - Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, - boolean isNested) { + protected ImmutablePair 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()); + log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), + oldResource.getLifecycleState()); ImmutablePair resourcePair = null; try { serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import"); - oldResource = serviceImportParseLogic - .prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false); + oldResource = serviceImportParseLogic.prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false); serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource); serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); - serviceImportParseLogic - .validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource, - AuditingActionEnum.IMPORT_RESOURCE, inTransaction); + serviceImportParseLogic.validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource, + AuditingActionEnum.IMPORT_RESOURCE, inTransaction); createNewResourceToOldResource(newResource, oldResource, user); - - Either overrideResource = toscaOperationFacade - .overrideComponent(newResource, oldResource); + Either overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource); if (overrideResource.isRight()) { ResponseFormat responseFormat = new ResponseFormat(); serviceBusinessLogic.throwComponentException(responseFormat); } log.debug("Resource updated successfully!!!"); - resourcePair = new ImmutablePair<>(overrideResource.left().value(), - ActionStatus.OK); + resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK); return resourcePair; } finally { if (resourcePair == null) { @@ -2697,8 +2457,7 @@ public class ServiceImportBusinessLogic { boolean needLock, Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts, - Map nodeTypesInfo, - CsarInfo csarInfo) { + Map nodeTypesInfo, CsarInfo csarInfo) { try { Either toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); @@ -2725,26 +2484,20 @@ public class ServiceImportBusinessLogic { Resource vfcCreated = null; while (nodesNameValueIter.hasNext()) { Map.Entry nodeType = nodesNameValueIter.next(); - Map> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null - || nodeTypesArtifactsToHandle.isEmpty() ? null - : nodeTypesArtifactsToHandle.get(nodeType.getKey()); - + Map> nodeTypeArtifactsToHandle = + nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey()); if (nodeTypesInfo.containsKey(nodeType.getKey())) { - vfcCreated = handleNestedVfc(service, - nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + vfcCreated = handleNestedVfc(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeType.getKey()); log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); - } else if (csarInfo.getCreatedNodesToscaResourceNames() != null - && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { + } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames() + .containsKey(nodeType.getKey())) { ImmutablePair resourceCreated = serviceImportParseLogic - .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, - service, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, - csarInfo, true); + .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, service, needLock, + nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true); log.debug("************* Finished to create node {}", nodeType.getKey()); - vfcCreated = resourceCreated.getLeft(); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), - vfcCreated.getName()); + csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getName()); } if (vfcCreated != null) { csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); @@ -2752,5 +2505,4 @@ public class ServiceImportBusinessLogic { mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()); } } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java index fa079d2f65..9fba1c7164 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; - import javax.servlet.ServletContext; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -30,79 +28,72 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; - //upload Service model by Shiyong1989@hotmail.com @Component("ServiceImportManager") public class ServiceImportManager { - private ServletContext servletContext; - - private ResponseFormatManager responseFormatManager; - - @Autowired - private ServiceBusinessLogic serviceBusinessLogic; - - public ServiceImportBusinessLogic getServiceImportBusinessLogic() { - return serviceImportBusinessLogic; - } - - public void setServiceImportBusinessLogic( - ServiceImportBusinessLogic serviceImportBusinessLogic) { - this.serviceImportBusinessLogic = serviceImportBusinessLogic; - } + private ServletContext servletContext; + private ResponseFormatManager responseFormatManager; + @Autowired + private ServiceBusinessLogic serviceBusinessLogic; + @Autowired + private ServiceImportBusinessLogic serviceImportBusinessLogic; - @Autowired - private ServiceImportBusinessLogic serviceImportBusinessLogic; - - public boolean isServiceExist(String serviceName) { - return serviceBusinessLogic.isServiceExist(serviceName); - } + public ServiceImportBusinessLogic getServiceImportBusinessLogic() { + return serviceImportBusinessLogic; + } + public void setServiceImportBusinessLogic(ServiceImportBusinessLogic serviceImportBusinessLogic) { + this.serviceImportBusinessLogic = serviceImportBusinessLogic; + } - public ServiceBusinessLogic getServiceBusinessLogic() { - return serviceBusinessLogic; - } + public boolean isServiceExist(String serviceName) { + return serviceBusinessLogic.isServiceExist(serviceName); + } - public void setServiceBusinessLogic( - ServiceBusinessLogic serviceBusinessLogic) { - this.serviceBusinessLogic = serviceBusinessLogic; - } + public ServiceBusinessLogic getServiceBusinessLogic() { + return serviceBusinessLogic; + } + public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) { + this.serviceBusinessLogic = serviceBusinessLogic; + } - public void populateServiceMetadata(UploadServiceInfo serviceMetaData, Service service) { - if (service != null && serviceMetaData != null) { - service.setDescription(serviceMetaData.getDescription()); - service.setTags(serviceMetaData.getTags()); - service.setCategories(serviceMetaData.getCategories()); - service.setContactId(serviceMetaData.getContactId()); - service.setName(serviceMetaData.getName()); - service.setIcon(serviceMetaData.getServiceIconPath()); - service.setServiceVendorModelNumber(serviceMetaData.getServiceVendorModelNumber()); - ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) service - .getComponentMetadataDefinition().getMetadataDataDefinition(); - serviceMetadataDataDefinition.getServiceVendorModelNumber(); - service.setServiceType(""); - service.setProjectCode(serviceMetaData.getProjectCode()); - if (serviceMetaData.getVendorName() != null) { - service.setVendorName(serviceMetaData.getVendorName()); - } - if (serviceMetaData.getVendorRelease() != null) { - service.setVendorRelease(serviceMetaData.getVendorRelease()); - } + public void populateServiceMetadata(UploadServiceInfo serviceMetaData, Service service) { + if (service != null && serviceMetaData != null) { + service.setDescription(serviceMetaData.getDescription()); + service.setTags(serviceMetaData.getTags()); + service.setCategories(serviceMetaData.getCategories()); + service.setContactId(serviceMetaData.getContactId()); + service.setName(serviceMetaData.getName()); + service.setIcon(serviceMetaData.getServiceIconPath()); + service.setServiceVendorModelNumber(serviceMetaData.getServiceVendorModelNumber()); + ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition() + .getMetadataDataDefinition(); + serviceMetadataDataDefinition.getServiceVendorModelNumber(); + service.setServiceType(""); + service.setProjectCode(serviceMetaData.getProjectCode()); + if (serviceMetaData.getVendorName() != null) { + service.setVendorName(serviceMetaData.getVendorName()); + } + if (serviceMetaData.getVendorRelease() != null) { + service.setVendorRelease(serviceMetaData.getVendorRelease()); + } + } } - } - public synchronized void init(ServletContext servletContext) { - if (this.servletContext == null) { - this.servletContext = servletContext; - responseFormatManager = ResponseFormatManager.getInstance(); - serviceBusinessLogic = getServiceBL(servletContext); + public synchronized void init(ServletContext servletContext) { + if (this.servletContext == null) { + this.servletContext = servletContext; + responseFormatManager = ResponseFormatManager.getInstance(); + serviceBusinessLogic = getServiceBL(servletContext); + } } - } - private ServiceBusinessLogic getServiceBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(ServiceBusinessLogic.class); - } + private ServiceBusinessLogic getServiceBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(ServiceBusinessLogic.class); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java index 6a5e5314f0..3404323c9d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.impl; import static java.util.stream.Collectors.joining; @@ -151,21 +150,17 @@ public class ServiceImportParseLogic { public Either>>, ResponseFormat> findNodeTypesArtifactsToHandle( Map nodeTypesInfo, CsarInfo csarInfo, Service oldResource) { - Map>> nodeTypesArtifactsToHandle = new HashMap<>(); - Either>>, ResponseFormat> nodeTypesArtifactsToHandleRes - = Either.left(nodeTypesArtifactsToHandle); - + Either>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either + .left(nodeTypesArtifactsToHandle); try { Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar()); - Map> extractedVfcToscaNames = - extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo); - log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", - oldResource.getName(), csarInfo.getCsarUUID()); - extractedVfcToscaNames - .forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource, - extractedVfcsArtifacts, - namespace, vfcToscaNames)); + Map> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo); + log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), + csarInfo.getCsarUUID()); + extractedVfcToscaNames.forEach( + (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource, + extractedVfcsArtifacts, namespace, vfcToscaNames)); } catch (Exception e) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); nodeTypesArtifactsToHandleRes = Either.right(responseFormat); @@ -174,45 +169,41 @@ public class ServiceImportParseLogic { return nodeTypesArtifactsToHandleRes; } - private Map> extractVfcToscaNames(Map nodeTypesInfo, - String vfResourceName, CsarInfo csarInfo) { + 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()) { Map.Entry nodeType = nodesNameEntry.next(); - ImmutablePair toscaResourceName = buildNestedToscaResourceName( - ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); + 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.VF.name(), vfResourceName, cvfc.getType())); + vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType())); } return vfcToscaNames; } - public String buildNodeTypeYaml(Map.Entry nodeNameValue, Map mapToConvert, - String nodeResourceType, CsarInfo csarInfo) { + public String buildNodeTypeYaml(Map.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()); + node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(), + nodeNameValue.getValue()); mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); - return yaml.dumpAsMap(mapToConvert); } - ImmutablePair buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, - String nodeTypeFullName) { + ImmutablePair buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) { String actualType; String actualVfName; if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) { @@ -228,24 +219,19 @@ public class ServiceImportParseLogic { if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { nameWithouNamespacePrefix = nodeTypeFullName; } else { - nameWithouNamespacePrefix = nodeTypeFullName - .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + 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)); + toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)); } else { toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)); } StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), - previousToscaResourceName - .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()) - .toString()); + previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString()); } catch (Exception e) { componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e); @@ -274,7 +260,6 @@ public class ServiceImportParseLogic { Map>> nodeTypesArtifactsToHandle, Service resource, Map> extractedVfcsArtifacts, String namespace, ImmutablePair vfcToscaNames) { - EnumMap> curNodeTypeArtifactsToHandle = null; log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft()); Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null); @@ -286,19 +271,19 @@ public class ServiceImportParseLogic { curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); } else if (curNodeType != null) { // delete all artifacts if have not received artifacts from + // csar try { curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class); List artifactsToDelete = new ArrayList<>(); // delete all informational artifacts - artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream() - .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) - .collect(toList())); + artifactsToDelete.addAll( + curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(toList())); // delete all deployment artifacts artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values()); if (!artifactsToDelete.isEmpty()) { - curNodeTypeArtifactsToHandle - .put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete); + curNodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete); } } catch (Exception e) { componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); @@ -311,10 +296,8 @@ public class ServiceImportParseLogic { } } - protected void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, - List artifactsToAdd) { - List vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName) - .collect(toList()); + protected void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, List artifactsToAdd) { + List vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList()); artifactsToAdd.stream().forEach(a -> { if (!vfcArtifactNames.contains(a.getArtifactName())) { vfcArtifacts.add(a); @@ -330,16 +313,14 @@ public class ServiceImportParseLogic { log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status); throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID()); } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) { - return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName) - .left() + return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName).left() .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st)); } return null; } - protected EnumMap> findNodeTypeArtifactsToHandle( - Resource curNodeType, List extractedArtifacts) { - + protected EnumMap> findNodeTypeArtifactsToHandle(Resource curNodeType, + List extractedArtifacts) { EnumMap> nodeTypeArtifactsToHandle = null; try { List artifactsToUpload = new ArrayList<>(extractedArtifacts); @@ -364,10 +345,8 @@ public class ServiceImportParseLogic { existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); } if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) { - existingArtifacts - .putAll(curNodeType.getArtifacts().entrySet() - .stream() - .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + existingArtifacts.putAll( + curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))); } return existingArtifacts; @@ -396,23 +375,19 @@ public class ServiceImportParseLogic { Map existingArtifacts) { try { if (!existingArtifacts.isEmpty()) { - extractedArtifacts.stream() - .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a)); + extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a)); artifactsToDelete.addAll(existingArtifacts.values()); } } catch (Exception e) { log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } - } protected void processNodeTypeArtifact(List artifactsToUpload, List artifactsToUpdate, Map existingArtifacts, ArtifactDefinition currNewArtifact) { - Optional foundArtifact = existingArtifacts.values() - .stream() - .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())) - .findFirst(); + Optional foundArtifact = existingArtifacts.values().stream() + .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst(); if (foundArtifact.isPresent()) { if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) { updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get()); @@ -420,9 +395,8 @@ public class ServiceImportParseLogic { artifactsToUpload.remove(currNewArtifact); } else { log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); - throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, - currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), - foundArtifact.get().getArtifactType()); + throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), + currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType()); } } } @@ -431,16 +405,13 @@ public class ServiceImportParseLogic { ArtifactDefinition foundArtifact) { if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { foundArtifact.setPayload(currNewArtifact.getPayloadData()); - foundArtifact.setPayloadData( - Base64.encodeBase64String(currNewArtifact.getPayloadData())); - foundArtifact.setArtifactChecksum(GeneralUtility - .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); + foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData())); + foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); artifactsToUpdate.add(foundArtifact); } } - public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, - List createdArtifacts, + public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List createdArtifacts, Either, ResponseFormat> eitherNonMetaArtifacts) { if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) { @@ -472,7 +443,6 @@ public class ServiceImportParseLogic { protected boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map allGroups, Set allGroupMembers) { - boolean stop = false; // In Case Not Group Stop if (!allGroups.containsKey(groupName)) { @@ -482,7 +452,6 @@ public class ServiceImportParseLogic { if (!stop) { GroupDefinition groupDefinition = allGroups.get(groupName); stop = MapUtils.isEmpty(groupDefinition.getMembers()); - } // In Case all group members already contained stop if (!stop) { @@ -497,19 +466,15 @@ public class ServiceImportParseLogic { return stop; } - public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, - Map nodesInfo) { - + public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map nodesInfo) { Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); csarInfo.addNodeToQueue(nodeName); - return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), - AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); + return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); } public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) { - validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction); validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction); validateLifecycleTypesCreate(user, resource, actionEnum); @@ -524,21 +489,20 @@ public class ServiceImportParseLogic { } else { resourceSystemName = resource.getSystemName(); } - resource.setToscaResourceName(CommonBeUtils - .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName)); + 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 resource; } - protected Either validateResourceType(User user, Resource resource, - AuditingActionEnum actionEnum) { + protected Either validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) { Either eitherResult = Either.left(true); if (resource.getResourceType() == null) { log.debug("Invalid resource type for resource"); @@ -549,8 +513,7 @@ public class ServiceImportParseLogic { return eitherResult; } - protected Either validateLifecycleTypesCreate(User user, Resource resource, - AuditingActionEnum actionEnum) { + protected 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"); @@ -558,21 +521,16 @@ public class ServiceImportParseLogic { while (intItr.hasNext() && eitherResult.isLeft()) { InterfaceDefinition interfaceDefinition = intItr.next(); String intType = interfaceDefinition.getUniqueId(); - Either eitherCapTypeFound = interfaceTypeOperation - .getInterface(intType); + 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()); + .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); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType); eitherResult = Either.right(errorResponse); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); } @@ -581,19 +539,14 @@ public class ServiceImportParseLogic { return eitherResult; } - public Either validateCapabilityTypesCreate(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, - AuditingActionEnum actionEnum, - boolean inTransaction) { - + public 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 (Map.Entry> typeEntry : resource.getCapabilities().entrySet()) { - - eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, - eitherResult, typeEntry, inTransaction); + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, + inTransaction); if (eitherResult.isRight()) { return Either.right(eitherResult.right().value()); } @@ -602,8 +555,8 @@ public class ServiceImportParseLogic { 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); + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, + eitherResult, type, inTransaction); if (eitherResult.isRight()) { return Either.right(eitherResult.right().value()); } @@ -612,9 +565,8 @@ public class ServiceImportParseLogic { return eitherResult; } - protected Either validateCapabilityTypeExists(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, - AuditingActionEnum actionEnum, + protected Either validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, + Resource resource, AuditingActionEnum actionEnum, Either eitherResult, Map.Entry> typeEntry, boolean inTransaction) { @@ -622,17 +574,13 @@ public class ServiceImportParseLogic { .getCapabilityType(typeEntry.getKey(), inTransaction); if (eitherCapTypeFound.isRight()) { if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( - CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "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_VALIDATE_CAPABILITY_TYPES); + .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "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_VALIDATE_CAPABILITY_TYPES); } - 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()); + 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); return Either.right(eitherResult.right().value()); @@ -668,9 +616,8 @@ public class ServiceImportParseLogic { return eitherResult; } - protected Either validateCapabilityTypeExists(User user, - ICapabilityTypeOperation capabilityTypeOperation, Resource resource, - List validationObjects, + protected Either validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, + Resource resource, List validationObjects, AuditingActionEnum actionEnum, Either eitherResult, String type, boolean inTransaction) { @@ -679,26 +626,21 @@ public class ServiceImportParseLogic { .getCapabilityType(type, inTransaction); if (eitherCapTypeFound.isRight()) { if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( - CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "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_VALIDATE_CAPABILITY_TYPES); + .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "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_VALIDATE_CAPABILITY_TYPES); } - log.debug("Trying to get capability type {} failed with error: {}", type, - eitherCapTypeFound.right().value().name()); + 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); + errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects); } eitherResult = Either.right(errorResponse); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); } - } catch (Exception e) { log.debug("Exception occured when validateCapabilityTypeExists, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, resource.getName()); @@ -706,8 +648,8 @@ public class ServiceImportParseLogic { return eitherResult; } - protected Either validateResourceFieldsBeforeCreate(User user, Resource resource, - AuditingActionEnum actionEnum, boolean inTransaction) { + protected Either validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, + boolean inTransaction) { serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum); // validate category log.debug("validate category"); @@ -736,22 +678,18 @@ public class ServiceImportParseLogic { if (currentCreatorFullName != null) { log.debug("Resource Creator fullname is automatically set and cannot be updated"); } - String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); if (currentLastUpdaterFullName != null) { log.debug("Resource LastUpdater fullname is automatically set and cannot be updated"); } - Long currentLastUpdateDate = resource.getLastUpdateDate(); if (currentLastUpdateDate != null) { log.debug("Resource last update date is automatically set and cannot be updated"); } - Boolean currentAbstract = resource.isAbstract(); if (currentAbstract != null) { log.debug("Resource abstract is automatically set and cannot be updated"); } - return Either.left(true); } @@ -760,8 +698,7 @@ public class ServiceImportParseLogic { return; } String templateName = resource.getDerivedFrom().get(0); - Either dataModelResponse = toscaOperationFacade - .validateToscaResourceNameExists(templateName); + Either dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName); if (dataModelResponse.isRight()) { StorageOperationStatus storageStatus = dataModelResponse.right().value(); BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist"); @@ -779,13 +716,11 @@ public class ServiceImportParseLogic { } } - protected void validateLicenseType(User user, Resource resource, - AuditingActionEnum actionEnum) { + protected void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate licenseType"); String licenseType = resource.getLicenseType(); if (licenseType != null) { - List licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration() - .getLicenseTypes(); + List licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes(); if (!licenseTypes.contains(licenseType)) { log.debug("License type {} isn't configured", licenseType); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -813,19 +748,18 @@ public class ServiceImportParseLogic { if (org.apache.commons.lang.StringUtils.isNotEmpty(resourceVendorModelNumber)) { if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) { log.info("resource vendor model number exceeds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat( - ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); } // 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); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); } @@ -841,7 +775,6 @@ public class ServiceImportParseLogic { componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE); } - validateVendorReleaseName(vendorRelease, user, resource, actionEnum); } @@ -849,12 +782,11 @@ public class ServiceImportParseLogic { 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); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); } - if (!ValidationUtils.validateVendorRelease(vendorRelease)) { log.info("vendor release is not valid."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); @@ -864,17 +796,14 @@ public class ServiceImportParseLogic { } } - protected void validateCategory(User user, Resource resource, - AuditingActionEnum actionEnum, boolean inTransaction) { - + protected void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { List categories = resource.getCategories(); if (CollectionUtils.isEmpty(categories)) { log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); + throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); } if (categories.size() > 1) { log.debug("Must be only one category for resource"); @@ -890,30 +819,26 @@ public class ServiceImportParseLogic { log.debug("Must be only one sub category for resource"); throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); } - SubCategoryDefinition subcategory = subcategories.get(0); - if (!ValidationUtils.validateStringNotEmpty(category.getName())) { log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); + throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); } if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { log.debug(CATEGORY_IS_EMPTY); - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, actionEnum); throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); } - validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction); } - protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, - User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { + protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource, + AuditingActionEnum actionEnum, boolean inTransaction) { ResponseFormat responseFormat; if (category != null && subcategory != null) { try { @@ -927,24 +852,17 @@ public class ServiceImportParseLogic { throw new ComponentException(categories.right().value()); } List categoryList = categories.left().value(); - Optional foundCategory = categoryList.stream() - .filter(cat -> cat.getName().equals(category.getName())) + Optional foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName())) .findFirst(); if (!foundCategory.isPresent()) { - log.debug( - "Category {} is not part of resource category group. Resource category valid values are {}", - category, categoryList); + log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList); failOnInvalidCategory(user, resource, actionEnum); } - Optional foundSubcategory = foundCategory.get() - .getSubcategories() - .stream() - .filter(subcat -> subcat.getName().equals(subcategory.getName())) - .findFirst(); + Optional foundSubcategory = foundCategory.get().getSubcategories().stream() + .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst(); if (!foundSubcategory.isPresent()) { - log.debug( - "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", - subcategory, foundCategory.get().getSubcategories()); + log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, + foundCategory.get().getSubcategories()); failOnInvalidCategory(user, resource, actionEnum); } } catch (Exception e) { @@ -956,15 +874,12 @@ public class ServiceImportParseLogic { protected void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) { ResponseFormat responseFormat; - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, - ComponentTypeEnum.RESOURCE.getValue()); + throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); } - protected void validateVendorName(User user, Resource resource, - AuditingActionEnum actionEnum) { + protected void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) { String vendorName = resource.getVendorName(); if (!ValidationUtils.validateStringNotEmpty(vendorName)) { log.info("vendor name is missing."); @@ -975,18 +890,15 @@ public class ServiceImportParseLogic { validateVendorName(vendorName, user, resource, actionEnum); } - protected void validateVendorName(String vendorName, User user, Resource resource, - AuditingActionEnum actionEnum) { + protected void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) { 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); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); componentsUtils.auditResource(errorResponse, user, resource, actionEnum); - throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, - "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); } - if (!ValidationUtils.validateVendorName(vendorName)) { log.info("vendor name is not valid."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME); @@ -996,8 +908,7 @@ public class ServiceImportParseLogic { } } - private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, - Map nodesInfo) { + 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)); @@ -1013,15 +924,11 @@ public class ServiceImportParseLogic { cvfc.setVendorName(resourceVf.getVendorName()); cvfc.setVendorRelease(resourceVf.getVendorRelease()); cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); - cvfc.setToscaResourceName( - buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName) - .getLeft()); + cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.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(); @@ -1030,17 +937,14 @@ public class ServiceImportParseLogic { 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 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); @@ -1051,54 +955,43 @@ public class ServiceImportParseLogic { return resourceName + "VF"; } - public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, - String nodeName, User user) { + public UploadResourceInfo 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); - throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, resourceMetaData.getName(), nodeName); + log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); } - 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()); - throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, resourceMetaData.getName(), nodeName); + log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values()); + throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); } - // 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); @@ -1108,13 +1001,11 @@ public class ServiceImportParseLogic { List categories = new ArrayList<>(); categories.add(category); resourceMetaData.setCategories(categories); - return resourceMetaData; } protected String getNodeTypeActualName(String fullName) { - String nameWithouNamespacePrefix = fullName - .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); String[] findTypes = nameWithouNamespacePrefix.split("\\."); String resourceType = findTypes[0]; return nameWithouNamespacePrefix.substring(resourceType.length()); @@ -1129,8 +1020,7 @@ public class ServiceImportParseLogic { public Either findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, - ComponentInstance currentCompInstance, - String capName) { + ComponentInstance currentCompInstance, String capName) { Map> comInstRegDefMap = currentCompInstance.getRequirements(); List list = comInstRegDefMap.get(capName); RequirementDefinition validRegDef = null; @@ -1138,8 +1028,7 @@ public class ServiceImportParseLogic { for (Map.Entry> entry : comInstRegDefMap.entrySet()) { for (RequirementDefinition reqDef : entry.getValue()) { if (reqDef.getName().equals(regName)) { - if (reqDef.getMaxOccurrences() != null - && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { String leftOccurrences = reqDef.getLeftOccurrences(); if (leftOccurrences == null) { leftOccurrences = reqDef.getMaxOccurrences(); @@ -1157,7 +1046,6 @@ public class ServiceImportParseLogic { validRegDef = reqDef; break; } - } } if (validRegDef != null) { @@ -1167,8 +1055,7 @@ public class ServiceImportParseLogic { } else { for (RequirementDefinition reqDef : list) { if (reqDef.getName().equals(regName)) { - if (reqDef.getMaxOccurrences() != null - && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { String leftOccurrences = reqDef.getLeftOccurrences(); if (leftOccurrences == null) { leftOccurrences = reqDef.getMaxOccurrences(); @@ -1190,18 +1077,18 @@ public class ServiceImportParseLogic { } } if (validRegDef == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), + uploadComponentInstanceInfo.getType()); return Either.right(responseFormat); } return Either.left(validRegDef); } - public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, - ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, + UploadReqInfo uploadReqInfo) { try { - if (null == uploadReqInfo.getCapabilityName() - || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) { + if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) { // get by capability type return findAvailableCapability(validReq, currentCapCompInstance); } @@ -1216,11 +1103,9 @@ public class ServiceImportParseLogic { Map> capMap = instance.getCapabilities(); if (capMap.containsKey(validReq.getCapability())) { List capList = capMap.get(validReq.getCapability()); - for (CapabilityDefinition cap : capList) { if (isBoundedByOccurrences(cap)) { - String leftOccurrences = cap.getLeftOccurrences() != null ? - cap.getLeftOccurrences() : cap.getMaxOccurrences(); + String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences(); int left = Integer.parseInt(leftOccurrences); if (left > 0) { --left; @@ -1235,8 +1120,8 @@ public class ServiceImportParseLogic { return null; } - protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, - ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, + UploadReqInfo uploadReqInfo) { CapabilityDefinition cap = null; Map> capMap = currentCapCompInstance.getCapabilities(); if (!capMap.containsKey(validReq.getCapability())) { @@ -1248,16 +1133,13 @@ public class ServiceImportParseLogic { return null; } cap = capByName.get(); - if (isBoundedByOccurrences(cap)) { String leftOccurrences = cap.getLeftOccurrences(); int left = Integer.parseInt(leftOccurrences); if (left > 0) { --left; cap.setLeftOccurrences(String.valueOf(left)); - } - } return cap; } @@ -1283,6 +1165,7 @@ public class ServiceImportParseLogic { parametersView.setIgnoreComponentInstances(false); parametersView.setIgnoreInputs(false); // inputs are read when creating + // property values on instances parametersView.setIgnoreUsers(false); return parametersView; @@ -1309,13 +1192,10 @@ public class ServiceImportParseLogic { if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) { defaultCapability = defaultCapabilities.get(capabilityType).get(0); } else { - Either getFullComponentRes = toscaOperationFacade - .getToscaFullElement(resourceId); + Either getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId); if (getFullComponentRes.isRight()) { - log.debug("Failed to get full component {}. Status is {}. ", resourceId, - getFullComponentRes.right().value()); - throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, - resourceId)); + log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value()); + throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId)); } defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0); } @@ -1323,33 +1203,27 @@ public class ServiceImportParseLogic { } protected void validateCapabilityProperties(List capabilities, String resourceId, CapabilityDefinition defaultCapability) { - if (CollectionUtils.isEmpty(defaultCapability.getProperties()) - && isNotEmpty(capabilities.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()); + if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.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()); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId)); } else if (isNotEmpty(capabilities.get(0).getProperties())) { validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0)); } } - protected void validateUniquenessUpdateUploadedComponentInstanceCapability( - CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) { + protected void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, + UploadCapInfo uploadedCapability) { List validProperties = new ArrayList<>(); Map defaultProperties = defaultCapability.getProperties().stream() - .collect(toMap(PropertyDefinition::getName, Function - .identity())); + .collect(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) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) { - throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, - propertyName)); + throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName)); } validProperty = new ComponentInstanceProperty(); validProperty.setName(propertyName); @@ -1381,15 +1255,14 @@ public class ServiceImportParseLogic { if (artifactMap == null) { artifactMap = new HashMap<>(); } - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration().getDeploymentResourceArtifacts(); + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getDeploymentResourceArtifacts(); if (deploymentResourceArtifacts != null) { Map finalArtifactMap = artifactMap; deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v)); } resource.setDeploymentArtifacts(artifactMap); } - } protected void processDeploymentResourceArtifacts(User user, Resource resource, Map artifactMap, String k, Object v) { @@ -1402,16 +1275,13 @@ public class ServiceImportParseLogic { return; } } else { - log.info("resource types for artifact placeholder {} were not defined. default is all resources", - k); + log.info("resource types for artifact placeholder {} were not defined. default is all resources", k); } if (shouldCreateArtifact) { if (serviceBusinessLogic.artifactsBusinessLogic != null) { - ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resource.getUniqueId(), k, (Map) v, - user, ArtifactGroupTypeEnum.DEPLOYMENT); - if (artifactDefinition != null - && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { + ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic + .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map) v, user, ArtifactGroupTypeEnum.DEPLOYMENT); + if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) { artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); } } @@ -1419,25 +1289,19 @@ public class ServiceImportParseLogic { } public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) { - if (newResource.getTags() == null || newResource.getTags().isEmpty()) { newResource.setTags(oldResource.getTags()); } - if (newResource.getDescription() == null) { newResource.setDescription(oldResource.getDescription()); } - if (newResource.getContactId() == null) { newResource.setContactId(oldResource.getContactId()); } - newResource.setCategories(oldResource.getCategories()); - } - protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, - Map nodesInfo) { + protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, Map nodesInfo) { Resource cvfc = new Resource(); NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); @@ -1453,15 +1317,11 @@ public class ServiceImportParseLogic { cvfc.setVendorName("cmri"); cvfc.setVendorRelease("1.0"); cvfc.setResourceVendorModelNumber(""); - cvfc.setToscaResourceName( - buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName) - .getLeft()); + cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.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(); @@ -1470,11 +1330,9 @@ public class ServiceImportParseLogic { 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; } @@ -1485,13 +1343,11 @@ public class ServiceImportParseLogic { private void 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())) { + 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); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); componentsUtils.auditResource(responseFormat, user, resource, actionEnum); - throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); } } @@ -1499,46 +1355,40 @@ public class ServiceImportParseLogic { public Service createInputsOnService(Service service, Map inputs) { List resourceProperties = service.getInputs(); if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) { - - Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, - service); + Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, service); if (createInputs.isRight()) { throw new ComponentException(createInputs.right().value()); } } else { return service; } - Either updatedResource = toscaOperationFacade - .getToscaElement(service.getUniqueId()); + Either updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId()); if (updatedResource.isRight()) { - throw new ComponentException(componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE)); + throw new ComponentException(componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, + ComponentTypeEnum.SERVICE)); } return updatedResource.left().value(); } - public Service createServiceTransaction(Service service, User user, boolean isNormative) { // validate resource name uniqueness log.debug("validate resource name"); - Either eitherValidation = toscaOperationFacade.validateComponentNameExists( - service.getName(), null, service.getComponentType()); + Either eitherValidation = toscaOperationFacade + .validateComponentNameExists(service.getName(), null, service.getComponentType()); if (eitherValidation.isRight()) { - log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), - eitherValidation.right().value()); + log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value()); ResponseFormat errorResponse = componentsUtils .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); throw new ComponentException(errorResponse); } if (eitherValidation.left().value()) { log.debug("resource with name: {}, already exists", service.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, - ComponentTypeEnum.RESOURCE.getValue(), service.getName()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName()); throw new ComponentException(errorResponse); } - log.debug("send resource {} to dao for create", service.getName()); - createArtifactsPlaceHolderData(service, user); // enrich object if (!isNormative) { @@ -1547,18 +1397,15 @@ public class ServiceImportParseLogic { service.setVersion(INITIAL_VERSION); service.setHighestVersion(true); } - return toscaOperationFacade.createToscaComponent(service) - .left() - .on(r -> throwComponentExceptionByResource(r, service)); + return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service)); } public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE); throw new ComponentException(responseFormat); } - protected void createArtifactsPlaceHolderData(Service service, User user) { setInformationalArtifactsPlaceHolder(service, user); serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user); @@ -1567,40 +1414,34 @@ public class ServiceImportParseLogic { @SuppressWarnings("unchecked") protected void setInformationalArtifactsPlaceHolder(Service service, User user) { - Map artifactMap = service.getArtifacts(); if (artifactMap == null) { artifactMap = new HashMap<>(); } String resourceUniqueId = service.getUniqueId(); - List exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludeResourceCategory(); - List exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration() - .getExcludeResourceType(); - Map informationalResourceArtifacts = ConfigurationManager.getConfigurationManager() - .getConfiguration().getInformationalResourceArtifacts(); + List exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory(); + List exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType(); + Map informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getInformationalResourceArtifacts(); List categories = service.getCategories(); boolean isCreateArtifact = true; if (exludeResourceCategory != null) { String category = categories.get(0).getName(); isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category)); } - if (informationalResourceArtifacts != null && isCreateArtifact) { Set keys = informationalResourceArtifacts.keySet(); for (String informationalResourceArtifactName : keys) { - Map artifactInfoMap = (Map) informationalResourceArtifacts - .get(informationalResourceArtifactName); + Map artifactInfoMap = (Map) informationalResourceArtifacts.get(informationalResourceArtifactName); if (serviceBusinessLogic.artifactsBusinessLogic != null) { - ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, - ArtifactGroupTypeEnum.INFORMATIONAL); + ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic + .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, + ArtifactGroupTypeEnum.INFORMATIONAL); artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); } } } service.setArtifacts(artifactMap); - } public void rollback(boolean inTransaction, Service service, List createdArtifacts, @@ -1615,48 +1456,40 @@ public class ServiceImportParseLogic { } public Map getNodeTypesFromTemplate(Map mappedToscaTemplate) { - return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES) - .left().orValue(HashMap::new); + return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new); } - private Resource nodeForceCertification(Resource resource, User user, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, - needLock); + private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, + boolean needLock) { + return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); } - private Resource nodeFullCertification(String uniqueId, User user, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, + boolean needLock) { Either resourceResponse = lifecycleBusinessLogic - .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, - inTransaction, needLock); + .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock); if (resourceResponse.isRight()) { throw new ByResponseFormatComponentException(resourceResponse.right().value()); } return resourceResponse.left().value(); } - public Either validateNestedDerivedFromDuringUpdate(Resource currentResource, - Resource updateInfoResource, boolean hasBeenCertified) { - + public 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()) { + 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) { validateDerivedFromExist(null, updateInfoResource, null); } else { - Either validateDerivedFromExtending = validateDerivedFromExtending(null, - currentResource, updateInfoResource, null); - + 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; @@ -1666,45 +1499,35 @@ public class ServiceImportParseLogic { return Either.left(true); } - protected Either validateDerivedFromExtending(User user, Resource currentResource, - Resource updateInfoResource, AuditingActionEnum actionEnum) { + protected 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); + 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); + 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 void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, - boolean inTransaction, boolean isNested) { + public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) { validateFields(currentResource, updateInfoResource, inTransaction, isNested); } - private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) { - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); log.debug("validate resource name before update"); validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested); @@ -1726,12 +1549,9 @@ public class ServiceImportParseLogic { } log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); log.debug("validate category before update"); - } - - protected void validateResourceName(Resource currentResource, Resource updateInfoResource, - boolean hasBeenCertified, boolean isNested) { + protected void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) { String resourceNameUpdated = updateInfoResource.getName(); if (!isResourceNameEquals(currentResource, updateInfoResource)) { if (isNested || !hasBeenCertified) { @@ -1739,10 +1559,8 @@ public class ServiceImportParseLogic { 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); + log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated); throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); } } @@ -1754,34 +1572,25 @@ public class ServiceImportParseLogic { if (resourceNameCurrent.equals(resourceNameUpdated)) { return true; } - return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && - resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent)); + return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated + .equals(addCvfcSuffixToResourceName(resourceNameCurrent)); } - public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, - boolean inTransaction, boolean needLock) { - + public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) { if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) { // checkout - return lifecycleBusinessLogic.changeState( - oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, - new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock) - .left() - .on(response -> failOnChangeState(response, user, oldResource, newResource)); + return lifecycleBusinessLogic + .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), + inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource)); } return oldResource; } protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) { if (response.getRequestError() != null) { - log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), - response.getFormattedMessage()); - + log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage()); componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, - ResourceVersionInfo.newBuilder() - .state(oldResource.getLifecycleState().name()) - .version(oldResource.getVersion()) - .build()); + ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build()); } throw new ComponentException(response); } @@ -1797,20 +1606,17 @@ public class ServiceImportParseLogic { public Resource createInputsOnResource(Resource resource, Map inputs) { List resourceProperties = resource.getInputs(); if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) { - - Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, - resource); + Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource); if (createInputs.isRight()) { throw new ComponentException(createInputs.right().value()); } } else { return resource; } - Either updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); + Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (updatedResource.isRight()) { - throw new ComponentException(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource)); + throw new ComponentException( + componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource)); } return updatedResource.left().value(); } @@ -1830,25 +1636,18 @@ public class ServiceImportParseLogic { if (isNotEmpty(groupsToCreate)) { fillGroupsFinalFields(groupsToCreate); if (isNotEmpty(groupsFromResource)) { - serviceBusinessLogic.groupBusinessLogic.addGroups(resource, - groupsToCreate, true) - .left() + serviceBusinessLogic.groupBusinessLogic.addGroups(resource, groupsToCreate, true).left() .on(serviceBusinessLogic::throwComponentException); } else { - serviceBusinessLogic.groupBusinessLogic.createGroups(resource, - groupsToCreate, true) - .left() + serviceBusinessLogic.groupBusinessLogic.createGroups(resource, groupsToCreate, true).left() .on(serviceBusinessLogic::throwComponentException); } } if (isNotEmpty(groupsToDelete)) { - serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete) - .left() - .on(serviceBusinessLogic::throwComponentException); + serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(serviceBusinessLogic::throwComponentException); } if (isNotEmpty(groupsToUpdate)) { - serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true) - .left() + serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left() .on(serviceBusinessLogic::throwComponentException); } } @@ -1856,8 +1655,8 @@ public class ServiceImportParseLogic { protected void addGroupsToCreateOrUpdate(List groupsFromResource, List groupsAsList, List groupsToUpdate, List groupsToCreate) { for (GroupDefinition group : groupsAsList) { - Optional op = groupsFromResource.stream() - .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny(); + Optional op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())) + .findAny(); if (op.isPresent()) { GroupDefinition groupToUpdate = op.get(); groupToUpdate.setMembers(group.getMembers()); @@ -1873,8 +1672,7 @@ public class ServiceImportParseLogic { protected void addGroupsToDelete(List groupsFromResource, List groupsAsList, List groupsToDelete) { for (GroupDefinition group : groupsFromResource) { - Optional op = groupsAsList.stream() - .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); + Optional op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) { groupsToDelete.add(group); } @@ -1882,10 +1680,8 @@ public class ServiceImportParseLogic { } protected List updateGroupsMembersUsingResource(Map groups, Service component) { - List result = new ArrayList<>(); List componentInstances = component.getComponentInstances(); - if (groups != null) { Either validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); if (validateCyclicGroupsDependencies.isRight()) { @@ -1909,42 +1705,35 @@ public class ServiceImportParseLogic { public void updateGroupMembers(Map groups, GroupDefinition updatedGroupDefinition, Service component, List componentInstances, String groupName, Map members) { Set compInstancesNames = members.keySet(); - if (CollectionUtils.isEmpty(componentInstances)) { String membersAstString = compInstancesNames.stream().collect(joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", - membersAstString, groupName, component.getNormalizedName()); - throw new ComponentException(componentsUtils.getResponseFormat( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, - component.getNormalizedName(), getComponentTypeForResponse(component))); + log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, + groupName, component.getNormalizedName()); + throw new ComponentException(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(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + Map memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> ""))); - Map relevantInstances = memberNames.entrySet().stream() - .filter(n -> compInstancesNames.contains(n.getKey())) + Map relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); - if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { - List foundMembers = new ArrayList<>(); if (relevantInstances != null) { foundMembers = relevantInstances.keySet().stream().collect(toList()); } compInstancesNames.removeAll(foundMembers); String membersAstString = compInstancesNames.stream().collect(joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, - groupName, component.getNormalizedName()); - throw new ComponentException(componentsUtils.getResponseFormat( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, - component.getNormalizedName(), getComponentTypeForResponse(component))); + log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName()); + throw new ComponentException(componentsUtils + .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), + getComponentTypeForResponse(component))); } updatedGroupDefinition.setMembers(relevantInstances); } public Either validateCyclicGroupsDependencies(Map allGroups) { - Either result = Either.left(true); try { Iterator> allGroupsItr = allGroups.entrySet().iterator(); @@ -1957,8 +1746,7 @@ public class ServiceImportParseLogic { 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); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName); result = Either.right(responseFormat); } } @@ -1970,9 +1758,7 @@ public class ServiceImportParseLogic { return result; } - protected void fillAllGroupMemebersRecursivly(String groupName, Map allGroups, - Set allGroupMembers) { - + protected void fillAllGroupMemebersRecursivly(String groupName, Map allGroups, Set allGroupMembers) { // Found Cyclic dependency if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { return; @@ -1981,6 +1767,7 @@ public class ServiceImportParseLogic { // 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 @@ -1989,7 +1776,6 @@ public class ServiceImportParseLogic { peek(allGroupMembers::add). // Collect results collect(toList()); - // Recursively call the method for all the filtered group members for (String innerGroupName : currGroupFilteredMembers) { fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers); @@ -2000,83 +1786,65 @@ public class ServiceImportParseLogic { boolean isInTransaction, boolean needLock, Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, - boolean forceCertificationAllowed, CsarInfo csarInfo, - String nodeName, boolean isNested) { - + boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, + boolean isNested) { LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); - - Function validator = resource -> validateResourceCreationFromNodeType( - resource, creator); - - return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, - lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, - nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); - } - - public ImmutablePair createNodeTypeResourceFromYaml( - String yamlName, Map.Entry nodeNameValue, User user, Map mapToConvert, - Service resourceVf, boolean needLock, - Map> nodeTypeArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, - boolean isNested) { - + Function validator = resource -> validateResourceCreationFromNodeType(resource, creator); + return resourceImportManager + .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, + nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); + } + + public ImmutablePair createNodeTypeResourceFromYaml(String yamlName, Map.Entry nodeNameValue, User user, + Map mapToConvert, Service resourceVf, + boolean needLock, + Map> nodeTypeArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, + boolean forceCertificationAllowed, CsarInfo csarInfo, + boolean isNested) { UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); - - String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, - resourceMetaData.getResourceType(), csarInfo); + String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo); user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); - return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, - nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, - nodeNameValue.getKey(), isNested); + return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle, + nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested); } - protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, - String nodeName, User user) { + protected UploadResourceInfo fillResourceMetadata(String yamlName, Service 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); - throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, resourceMetaData.getName(), nodeName); + log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); } - 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()); - throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, resourceMetaData.getName(), nodeName); + log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values()); + throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); } - // 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()); - // 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); @@ -2086,24 +1854,20 @@ public class ServiceImportParseLogic { List categories = new ArrayList<>(); categories.add(category); resourceMetaData.setCategories(categories); - return resourceMetaData; } - - public Resource propagateStateToCertified(User user, Resource resource, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, - boolean forceCertificationAllowed) { - + public Resource 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())) { + if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic + .isFirstCertification(resource.getVersion())) { nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); } if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { - Either eitherPopulated = serviceBusinessLogic.populateToscaArtifacts( - resource, user, false, inTransaction, needLock); + Either eitherPopulated = serviceBusinessLogic + .populateToscaArtifacts(resource, user, false, inTransaction, needLock); return resource; } return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); @@ -2122,14 +1886,11 @@ public class ServiceImportParseLogic { } } - public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, - Map nodesInfo) { - + public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map nodesInfo) { Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo); log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); csarInfo.addNodeToQueue(nodeName); - return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), - AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); + return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); } public Resource updateGroupsOnResource(Resource resource, Map groups) { @@ -2138,28 +1899,24 @@ public class ServiceImportParseLogic { } else { updateOrCreateGroups(resource, groups); } - Either updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); + Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (updatedResource.isRight()) { - throw new ComponentException(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource)); + throw new ComponentException( + componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource)); } return updatedResource.left().value(); } protected 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 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) { @@ -2173,18 +1930,16 @@ public class ServiceImportParseLogic { if (informationalResourceArtifacts != null && isCreateArtifact) { Set keys = informationalResourceArtifacts.keySet(); for (String informationalResourceArtifactName : keys) { - Map artifactInfoMap = (Map) informationalResourceArtifacts - .get(informationalResourceArtifactName); + Map artifactInfoMap = (Map) informationalResourceArtifacts.get(informationalResourceArtifactName); if (serviceBusinessLogic.artifactsBusinessLogic != null) { - ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo( - resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, - ArtifactGroupTypeEnum.INFORMATIONAL); + ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic + .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, + ArtifactGroupTypeEnum.INFORMATIONAL); artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); } } } resource.setArtifacts(artifactMap); - } public void rollback(boolean inTransaction, Resource resource, List createdArtifacts, @@ -2207,10 +1962,7 @@ public class ServiceImportParseLogic { public void handleGroupsProperties(Service service, Map groups) { List inputs = service.getInputs(); if (MapUtils.isNotEmpty(groups)) { - groups.values() - .stream() - .filter(g -> isNotEmpty(g.getProperties())) - .flatMap(g -> g.getProperties().stream()) + groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream()) .forEach(p -> handleGetInputs(p, inputs)); } } @@ -2218,10 +1970,7 @@ public class ServiceImportParseLogic { public void handleGroupsProperties(Resource resource, Map groups) { List inputs = resource.getInputs(); if (MapUtils.isNotEmpty(groups)) { - groups.values() - .stream() - .filter(g -> isNotEmpty(g.getProperties())) - .flatMap(g -> g.getProperties().stream()) + groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream()) .forEach(p -> handleGetInputs(p, inputs)); } } @@ -2230,10 +1979,8 @@ public class ServiceImportParseLogic { if (isNotEmpty(property.getGetInputValues())) { if (inputs == null || inputs.isEmpty()) { log.debug("Failed to add property {} to group. Inputs list is empty ", property); - serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() - .stream() - .map(GetInputValueDataDefinition::getInputName) - .collect(toList()).toString()); + serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, + property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString()); } ListIterator getInputValuesIter = property.getGetInputValues().listIterator(); while (getInputValuesIter.hasNext()) { @@ -2251,9 +1998,7 @@ public class ServiceImportParseLogic { } public InputDefinition findInputByName(List inputs, GetInputValueDataDefinition getInput) { - Optional inputOpt = inputs.stream() - .filter(p -> p.getName().equals(getInput.getInputName())) - .findFirst(); + Optional inputOpt = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findFirst(); if (!inputOpt.isPresent()) { log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName()); serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName()); @@ -2267,10 +2012,9 @@ public class ServiceImportParseLogic { 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()); - throw new ComponentException(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName)); + log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value()); + throw new ComponentException( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName)); } } catch (Exception e) { log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage()); @@ -2284,71 +2028,55 @@ public class ServiceImportParseLogic { 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()); - throw new ComponentException(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName)); + log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value()); + throw new ComponentException( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName)); } } } public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map> instDeploymentArtifacts) { - StorageOperationStatus addArtToInst = toscaOperationFacade - .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); + StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public void associateArtifactsToInstances(String yamlName, Resource resource, Map> instArtifacts) { - StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map>> instCapabilities, Map>> instRequirements) { - StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, - resource); + addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map> instAttributes) { - StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, - resource); + addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public Resource getResourceAfterCreateRelations(Resource resource) { ComponentParametersView parametersView = getComponentFilterAfterCreateRelations(); - Either eitherGetResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId(), parametersView); - + Either eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); if (eitherGetResource.isRight()) { throwComponentExceptionByResource(eitherGetResource.right().value(), resource); } @@ -2356,8 +2084,7 @@ public class ServiceImportParseLogic { } public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(status), resource); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource); throw new ComponentException(responseFormat); } @@ -2380,10 +2107,9 @@ public class ServiceImportParseLogic { } } - public Map> getValidComponentInstanceCapabilities( - String resourceId, Map> defaultCapabilities, - Map> uploadedCapabilities) { - + public Map> getValidComponentInstanceCapabilities(String resourceId, + Map> defaultCapabilities, + Map> uploadedCapabilities) { Map> validCapabilitiesMap = new HashMap<>(); uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap)); return validCapabilitiesMap; @@ -2394,10 +2120,9 @@ public class ServiceImportParseLogic { Either>, StorageOperationStatus> addInputToInst = toscaOperationFacade .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId()); if (addInputToInst.isRight()) { - log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), - addInputToInst.right().value()); - throw new ComponentException(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName)); + log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value()); + throw new ComponentException( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName)); } } } @@ -2407,30 +2132,26 @@ public class ServiceImportParseLogic { Either>, StorageOperationStatus> addPropToInst = toscaOperationFacade .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId()); if (addPropToInst.isRight()) { - throw new ComponentException(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName)); + throw new ComponentException( + componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName)); } } public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource, Map> instDeploymentArtifacts) { - StorageOperationStatus addArtToInst = toscaOperationFacade - .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); + StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public void associateArtifactsToInstances(String yamlName, Service resource, Map> instArtifacts) { StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } @@ -2438,86 +2159,66 @@ public class ServiceImportParseLogic { Map>> instCapabilities, Map>> instRequirements) { StorageOperationStatus addArtToInst; - addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, - resource); - log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", - instCapabilities, instRequirements); + addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource); + log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", instCapabilities, instRequirements); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public void associateInstAttributeToComponentToInstances(String yamlName, Service resource, Map> instAttributes) { StorageOperationStatus addArtToInst; - - addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, - resource); + addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName)); } } public void associateRequirementsToService(String yamlName, Service resource, Map requirements) { StorageOperationStatus addReqToService; - addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, - resource.getUniqueId()); + addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, resource.getUniqueId()); if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), - addReqToService); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName)); + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addReqToService); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName)); } } public void associateCapabilitiesToService(String yamlName, Service resource, Map capabilities) { StorageOperationStatus addCapToService; - addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, - resource.getUniqueId()); + addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, resource.getUniqueId()); if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), - addCapToService); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName)); + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addCapToService); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName)); } } public void associateResourceInstances(String yamlName, Service service, List relations) { Either, StorageOperationStatus> relationsEither = toscaOperationFacade .associateResourceInstances(service, service.getUniqueId(), relations); - if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) { StorageOperationStatus status = relationsEither.right().value(); - log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), - status); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName)); + log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName)); } } public void addCapabilities(Map> originCapabilities, String type, List capabilities) { - List list = capabilities.stream().map(CapabilityDefinition::new) - .collect(toList()); + List list = capabilities.stream().map(CapabilityDefinition::new).collect(toList()); originCapabilities.put(type, list); } public void addCapabilitiesProperties(Map> newPropertiesMap, List capabilities) { for (UploadCapInfo capability : capabilities) { if (isNotEmpty(capability.getProperties())) { - newPropertiesMap.put(capability.getName(), capability.getProperties().stream() - .collect(toMap(UploadInfo::getName, p -> p))); + newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p))); } } } public Service getServiceWithGroups(String resourceId) { - ComponentParametersView filter = new ComponentParametersView(); filter.setIgnoreGroups(false); Either updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter); @@ -2528,7 +2229,6 @@ public class ServiceImportParseLogic { } public Resource getResourceWithGroups(String resourceId) { - ComponentParametersView filter = new ComponentParametersView(); filter.setIgnoreGroups(false); Either updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter); @@ -2539,15 +2239,12 @@ public class ServiceImportParseLogic { } public void associateResourceInstances(String yamlName, Resource resource, List relations) { - Either, StorageOperationStatus> relationsEither = toscaOperationFacade .associateResourceInstances(resource, resource.getUniqueId(), relations); if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) { StorageOperationStatus status = relationsEither.right().value(); - log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), - status); - throw new ComponentException(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName)); + log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status); + throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName)); } } @@ -2557,23 +2254,19 @@ public class ServiceImportParseLogic { 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(), BeEcompErrorManager.ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + 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(), + BeEcompErrorManager.ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); throw new ComponentException(responseFormat); } - ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); if (addRelationToRiRes.getStatus() != 200) { throw new ComponentException(addRelationToRiRes); @@ -2581,30 +2274,25 @@ public class ServiceImportParseLogic { } } - protected ResponseFormat addRelationToRI(String yamlName, Resource resource, - UploadComponentInstanceInfo nodesInfoValue, List relations) { + protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, + List relations) { List componentInstancesList = resource.getComponentInstances(); ComponentInstance currentCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - if (compInstance.getName().equals(nodesInfoValue.getName())) { currentCompInstance = compInstance; break; } } if (currentCompInstance == null) { - log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), - resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, - resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); - return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, - yamlName); + log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId()); + BeEcompErrorManager.getInstance() + .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(), + BeEcompErrorManager.ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } String resourceInstanceId = currentCompInstance.getUniqueId(); Map> regMap = nodesInfoValue.getRequirements(); - if (regMap != null) { Iterator>> nodesRegValue = regMap.entrySet().iterator(); while (nodesRegValue.hasNext()) { @@ -2616,16 +2304,13 @@ public class ServiceImportParseLogic { RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); regCapRelDef.setFromNode(resourceInstanceId); log.debug("try to find available requirement {} ", regName); - Either eitherReqStatus = findAviableRequiremen(regName, - yamlName, nodesInfoValue, currentCompInstance, - uploadRegInfo.getCapabilityName()); + Either eitherReqStatus = findAviableRequiremen(regName, yamlName, nodesInfoValue, + currentCompInstance, uploadRegInfo.getCapabilityName()); if (eitherReqStatus.isRight()) { return eitherReqStatus.right().value(); } - RequirementDefinition validReq = eitherReqStatus.left().value(); - List reqAndRelationshipPairList = regCapRelDef - .getRelationships(); + List reqAndRelationshipPairList = regCapRelDef.getRelationships(); if (reqAndRelationshipPairList == null) { reqAndRelationshipPairList = new ArrayList<>(); } @@ -2636,7 +2321,6 @@ public class ServiceImportParseLogic { RelationshipImpl relationship = new RelationshipImpl(); relationship.setType(validReq.getCapability()); reqAndRelationshipPair.setRelationships(relationship); - ComponentInstance currentCapCompInstance = null; for (ComponentInstance compInstance : componentInstancesList) { if (compInstance.getName().equals(uploadRegInfo.getNode())) { @@ -2644,30 +2328,24 @@ public class ServiceImportParseLogic { 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(), BeEcompErrorManager.ErrorSeverity.ERROR); - return componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + 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(), + BeEcompErrorManager.ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); log.debug("try to find aviable Capability req name is {} ", validReq.getName()); - CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, - currentCapCompInstance, uploadRegInfo); + CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo); reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); if (aviableCapForRel == null) { BeEcompErrorManager.getInstance().logInternalDataError( - "aviable capability was not found. req name is " + validReq.getName() - + " component instance is " + currentCapCompInstance.getUniqueId(), - resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); - return componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance + .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); + return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); capReqRel.setRelation(reqAndRelationshipPair); @@ -2681,5 +2359,4 @@ public class ServiceImportParseLogic { } return componentsUtils.getResponseFormat(ActionStatus.OK); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java index d6b17ca604..576dc41ccc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java @@ -16,9 +16,13 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; +import static java.util.stream.Collectors.toList; +import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue; + +import java.util.List; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.csar.CsarInfo; import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; @@ -33,18 +37,12 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Optional; - -import static java.util.stream.Collectors.toList; -import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue; - @Component("softwareInformationBusinessLogic") public class SoftwareInformationBusinessLogic { - private final PropertyBusinessLogic propertyBusinessLogic; private static final String SOFTWARE_VERSION_PROPERTY_NAME = "software_versions"; private static final String DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME = "default_software_version"; + private final PropertyBusinessLogic propertyBusinessLogic; @Autowired public SoftwareInformationBusinessLogic(final PropertyBusinessLogic propertyBusinessLogic) { @@ -53,17 +51,16 @@ public class SoftwareInformationBusinessLogic { /** * Adds the software information from a csar package to the resource {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} - * property.
The csar package must contain the expected non-mano yaml file with the software information. Also - * the resource must have the {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property. + * property.
The csar package must contain the expected non-mano yaml file with the software information. Also the resource must have the + * {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property. * * @param resource the resource to add the software information * @param csarInfo the csar package representation - * @return if the expected property exists in the resource and the csar package contains the software information - * file, an Optional with the updated property; otherwise Optional.empty(). + * @return if the expected property exists in the resource and the csar package contains the software information file, an + * Optional with the updated property; otherwise Optional.empty(). * @throws BusinessLogicException when there was a problem while updating the property */ - public Optional setSoftwareInformation(final Resource resource, - final CsarInfo csarInfo) throws BusinessLogicException { + public Optional setSoftwareInformation(final Resource resource, final CsarInfo csarInfo) throws BusinessLogicException { final Optional softwareInformation = csarInfo.getSoftwareInformationPath(); if (!softwareInformation.isPresent()) { return Optional.empty(); @@ -73,26 +70,22 @@ public class SoftwareInformationBusinessLogic { return Optional.empty(); } final byte[] softwareInformationYaml = csarInfo.getCsar().get(softwareInformation.get()); - final PnfSoftwareInformation pnfSoftwareInformation = - parseSoftwareInformation(softwareInformationYaml).orElse(null); + final PnfSoftwareInformation pnfSoftwareInformation = parseSoftwareInformation(softwareInformationYaml).orElse(null); if (pnfSoftwareInformation == null) { return Optional.empty(); } - - final List versionList = pnfSoftwareInformation.getSoftwareVersionSet().stream() - .map(PnfSoftwareVersion::getVersion).collect(toList()); - final String softwareVersionInformation = - getPropertyJsonStringValue(versionList, ToscaPropertyType.LIST.getType()); + final List versionList = pnfSoftwareInformation.getSoftwareVersionSet().stream().map(PnfSoftwareVersion::getVersion) + .collect(toList()); + final String softwareVersionInformation = getPropertyJsonStringValue(versionList, ToscaPropertyType.LIST.getType()); propertyDefinition.setValue(softwareVersionInformation); - - final PropertyDefinition updatedPropertyDefinition = - propertyBusinessLogic.updateComponentProperty(resource.getUniqueId(), propertyDefinition); - + final PropertyDefinition updatedPropertyDefinition = propertyBusinessLogic + .updateComponentProperty(resource.getUniqueId(), propertyDefinition); // set default-software-version as first entry of software version list for resource type pnf - if(resource.getResourceType() == ResourceTypeEnum.PNF && !versionList.isEmpty()){ + if (resource.getResourceType() == ResourceTypeEnum.PNF && !versionList.isEmpty()) { final String sw_version = versionList.get(0); - Optional default_Sw_Ver_PropertyDefinition = resource.safeGetInputs().stream().filter(s->DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME.equals(s.getName())).findFirst(); - if(default_Sw_Ver_PropertyDefinition.isPresent()) { + Optional default_Sw_Ver_PropertyDefinition = resource.safeGetInputs().stream() + .filter(s -> DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME.equals(s.getName())).findFirst(); + if (default_Sw_Ver_PropertyDefinition.isPresent()) { default_Sw_Ver_PropertyDefinition.get().setDefaultValue(sw_version); } } @@ -103,8 +96,7 @@ public class SoftwareInformationBusinessLogic { * Parses the non-mano software information yaml file. * * @param softwareInformationYaml the file byte array - * @return an {@code Optional} if the file was successful parsed, otherwise {@code - * Optional.empty()} + * @return an {@code Optional} if the file was successful parsed, otherwise {@code Optional.empty()} */ private Optional parseSoftwareInformation(byte[] softwareInformationYaml) { return SoftwareInformationArtifactYamlParser.parse(softwareInformationYaml); @@ -112,6 +104,7 @@ public class SoftwareInformationBusinessLogic { /** * Finds the {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property in a Resource + * * @param resource the resource to search for the property * @return an {@code Optional} if the property was found, otherwise {@code Optional.empty()} */ @@ -119,8 +112,7 @@ public class SoftwareInformationBusinessLogic { if (CollectionUtils.isEmpty(resource.getProperties())) { return Optional.empty(); } - return resource.getProperties().stream() - .filter(propertyDefinition -> propertyDefinition.getName().equals(SOFTWARE_VERSION_PROPERTY_NAME)) + return resource.getProperties().stream().filter(propertyDefinition -> propertyDefinition.getName().equals(SOFTWARE_VERSION_PROPERTY_NAME)) .findFirst(); } @@ -135,7 +127,6 @@ public class SoftwareInformationBusinessLogic { if (!softwareInformation.isPresent()) { return false; } - csarInfo.getCsar().remove(softwareInformation.get()); return true; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java index 538f565917..252c58d3e7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl; import java.util.Arrays; @@ -42,17 +41,15 @@ import org.togglz.core.util.NamedFeature; public class TogglingBusinessLogic extends BaseBusinessLogic { @Autowired - public TogglingBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, - interfaceLifecycleTypeOperation, artifactToscaOperation); + public TogglingBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); } public Map getAllFeatureStates() { - return Arrays.stream(ToggleableFeature.values()).collect(Collectors.toMap(Enum::name, - ToggleableFeature::isActive)); + return Arrays.stream(ToggleableFeature.values()).collect(Collectors.toMap(Enum::name, ToggleableFeature::isActive)); } public boolean getFeatureState(String featureName) { @@ -60,8 +57,7 @@ public class TogglingBusinessLogic extends BaseBusinessLogic { } public void setAllFeatures(boolean state) { - Arrays.asList(ToggleableFeature.values()) - .forEach(toggleableFeature -> updateFeatureState(toggleableFeature.name(), state)); + Arrays.asList(ToggleableFeature.values()).forEach(toggleableFeature -> updateFeatureState(toggleableFeature.name(), state)); } public void updateFeatureState(String featureName, boolean state) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java index 9c952415a3..4dc8c98e49 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.aaf; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; @@ -25,39 +24,35 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; public enum AafPermission { - - READ(PermNames.READ_VALUE), - WRITE(PermNames.WRITE_VALUE), - DELETE(PermNames.DELETE_VALUE), - INTERNAL_ALL(PermNames.INTERNAL_ALL_VALUE); - + READ(PermNames.READ_VALUE), WRITE(PermNames.WRITE_VALUE), DELETE(PermNames.DELETE_VALUE), INTERNAL_ALL(PermNames.INTERNAL_ALL_VALUE); private String permission; private String permissionSuffix; AafPermission(String permissionSuffix) { this.permissionSuffix = permissionSuffix; - this.permission = String.format("%s.%s", - ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace(), - permissionSuffix); - } - - public String getFullPermission() { - return permission; + this.permission = String + .format("%s.%s", ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace(), permissionSuffix); } public static AafPermission getEnumByString(String perm) { for (AafPermission e : AafPermission.values()) { - if (perm.equals(e.getPermissionSuffix())) + if (perm.equals(e.getPermissionSuffix())) { return e; + } } throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY, perm); } + public String getFullPermission() { + return permission; + } + public String getPermissionSuffix() { return this.permissionSuffix; } public static class PermNames { + public static final String READ_VALUE = "endpoint.api.access|*|read"; public static final String WRITE_VALUE = "endpoint.api.access|*|write"; public static final String DELETE_VALUE = "endpoint.api.access|*|delete"; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java index 34ca5965a1..95cebcacdc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java @@ -17,24 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.aaf; import org.openecomp.sdc.be.config.ConfigurationManager; public enum AafRoles { + READ_ONLY("app.readonly"), ALL("app.all"); + private String role; - READ_ONLY("app.readonly"), - ALL("app.all"); - - private String role; - - AafRoles(String roleSuffix) { - this.role = ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace() + "." + roleSuffix; - } - - public String getRole() { - return role; - } + AafRoles(String roleSuffix) { + this.role = ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace() + "." + roleSuffix; + } + public String getRole() { + return role; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java index a963e5e533..782e2ea8c2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.aaf; import java.lang.annotation.ElementType; @@ -28,5 +27,6 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PermissionAllowed { + String[] value(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java index b963cf6135..bc66a8c67e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java @@ -17,10 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.aaf; - +import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @@ -31,19 +30,15 @@ import org.openecomp.sdc.be.servlets.BeGenericServlet; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import javax.servlet.http.HttpServletRequest; - // aop id defined via application-context.xml. the annotations are only for test purposes @Aspect public class RoleAuthorizationHandler { private static final Logger log = Logger.getLogger(RoleAuthorizationHandler.class); - private final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); @Before("@annotation(permissions)") public void authorizeRole(JoinPoint joinPoint, PermissionAllowed permissions) { - if (isPermissionAuthenticationNeeded()) { String methodName = joinPoint.getSignature().toShortString(); HttpServletRequest request = ((BeGenericServlet) joinPoint.getThis()).getServletRequest(); @@ -58,13 +53,12 @@ public class RoleAuthorizationHandler { logAuth(methodName, perms, false, false); throw new ByActionStatusComponentException(ActionStatus.AUTH_FAILED); } - } private void logAuth(String methodName, String[] perms, boolean beforeAuth, Boolean success) { - if (beforeAuth) + if (beforeAuth) { log.trace("#{} - authorizing before invoking endpoint {}", methodName); - else { + } else { String status = success ? "SUCCESS" : "FAILED"; log.trace("#{} - authorizing before invoking endpoint {}, Status: {}", methodName, status); } @@ -77,6 +71,8 @@ public class RoleAuthorizationHandler { private boolean isPermissionAuthenticationNeeded() { if (configurationManager.getConfiguration().getAafAuthNeeded() && ThreadLocalsHolder.isExternalRequest()) { return true; - } else return false; + } else { + return false; + } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java index 84316dbdff..be529fe113 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.artifact; import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE; @@ -34,8 +33,7 @@ public final class ArtifactOperationInfo { private final boolean isExternalApi; private final boolean ignoreLifecycleState; - public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, - ArtifactOperationEnum artifactOperationEnum) { + public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) { this.artifactOperationEnum = artifactOperationEnum; this.isExternalApi = isExternalApi; this.ignoreLifecycleState = ignoreLifecycleState; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java index 3e3b9e260f..3362686ef3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java @@ -19,15 +19,8 @@ * * ============LICENSE_END========================================================= * */ - package org.openecomp.sdc.be.components.impl.artifact; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - import static org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum.HEAT_YAML; import static org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum.NOT_DEFINED; import static org.openecomp.sdc.common.api.ArtifactTypeEnum.DCAE_INVENTORY_JSON; @@ -47,6 +40,11 @@ import static org.openecomp.sdc.common.api.ArtifactTypeEnum.VF_LICENSE; import static org.openecomp.sdc.common.api.ArtifactTypeEnum.VNF_CATALOG; import static org.openecomp.sdc.common.api.ArtifactTypeEnum.YANG_XML; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; + public class ArtifactTypeToPayloadTypeSelector { private static final Map artifactTypeWithExtension2PayloadType = new HashMap<>(); @@ -66,17 +64,14 @@ public class ArtifactTypeToPayloadTypeSelector { artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, JSON), PayloadTypeEnum.JSON); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, YML), PayloadTypeEnum.YAML); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, YAML), PayloadTypeEnum.YAML); - artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, XML), PayloadTypeEnum.XML); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, JSON), PayloadTypeEnum.JSON); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, YML), PayloadTypeEnum.YAML); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, YAML), PayloadTypeEnum.YAML); - artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, XML), PayloadTypeEnum.XML); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, JSON), PayloadTypeEnum.JSON); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, YML), PayloadTypeEnum.YAML); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, YAML), PayloadTypeEnum.YAML); - artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, XML), PayloadTypeEnum.XML); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, JSON), PayloadTypeEnum.JSON); artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, YML), PayloadTypeEnum.YAML); @@ -88,7 +83,6 @@ public class ArtifactTypeToPayloadTypeSelector { artifactType2PayloadType.put(HEAT_VOL.getType().toLowerCase(), HEAT_YAML); artifactType2PayloadType.put(HEAT_NET.getType().toLowerCase(), HEAT_YAML); artifactType2PayloadType.put(HEAT_ENV.getType().toLowerCase(), PayloadTypeEnum.HEAT_ENV); - artifactType2PayloadType.put(YANG_XML.getType().toLowerCase(), PayloadTypeEnum.XML); artifactType2PayloadType.put(VNF_CATALOG.getType().toLowerCase(), PayloadTypeEnum.XML); artifactType2PayloadType.put(VF_LICENSE.getType().toLowerCase(), PayloadTypeEnum.XML); @@ -114,6 +108,7 @@ public class ArtifactTypeToPayloadTypeSelector { } private class ArtifactTypeWithExtension { + private String artifactType; private String fileExtension; @@ -136,9 +131,8 @@ public class ArtifactTypeToPayloadTypeSelector { return false; } ArtifactTypeWithExtension otherArtifactTypeWithExtension = (ArtifactTypeWithExtension) other; - - return isArtifactTypeEqual(otherArtifactTypeWithExtension.getArtifactType()) && - isFileExtensionEqual(otherArtifactTypeWithExtension.getFileExtension()); + return isArtifactTypeEqual(otherArtifactTypeWithExtension.getArtifactType()) && isFileExtensionEqual( + otherArtifactTypeWithExtension.getFileExtension()); } @Override diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java index 4a71d4bc86..b94b565d79 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java @@ -19,13 +19,17 @@ * * ============LICENSE_END========================================================= * * Modifications copyright (c) 2020 Nokia */ - package org.openecomp.sdc.be.components.impl.artifact; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fj.data.Either; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import javax.xml.XMLConstants; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.common.log.wrappers.Logger; @@ -36,12 +40,6 @@ import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; -import javax.xml.XMLConstants; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParserFactory; -import java.io.ByteArrayInputStream; -import java.io.IOException; - public enum PayloadTypeEnum { HEAT_YAML { @Override @@ -50,9 +48,7 @@ public enum PayloadTypeEnum { if (isNotValidYaml(payload, yamlToObjectConverter)) { return Either.right(ActionStatus.INVALID_YAML); } - - DeploymentArtifactHeatConfiguration heatConfiguration = - yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class); + DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class); if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) { log.debug("HEAT doesn't contain required \"heat_template_version\" section."); return Either.right(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT); @@ -68,8 +64,7 @@ public enum PayloadTypeEnum { private boolean isNotValidYaml(byte[] payload, YamlToObjectConverter yamlToObjectConverter) { return !yamlToObjectConverter.isValidYaml(payload); } - }, - HEAT_ENV { + }, HEAT_ENV { @Override public Either isValid(byte[] payload) { return isValidYaml(payload); @@ -79,8 +74,7 @@ public enum PayloadTypeEnum { public boolean isHeatRelated() { return true; } - }, - XML { + }, XML { @Override public Either isValid(byte[] payload) { try { @@ -103,11 +97,10 @@ public enum PayloadTypeEnum { reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (SAXNotRecognizedException exception) { log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", - exception.getMessage(), exception); + exception.getMessage(), exception); } } - }, - JSON { + }, JSON { @Override public Either isValid(byte[] payload) { try { @@ -118,29 +111,20 @@ public enum PayloadTypeEnum { } return Either.left(true); } - }, - YAML { + }, YAML { @Override public Either isValid(byte[] payload) { return isValidYaml(payload); } - }, - NOT_DEFINED { + }, NOT_DEFINED { @Override public Either isValid(byte[] payload) { return Either.left(true); } }; - private static final Logger log = Logger.getLogger(PayloadTypeEnum.class); private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - public abstract Either isValid(byte[] payload); - - public boolean isHeatRelated() { - return false; - } - private static Either isValidYaml(byte[] payload) { YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); if (yamlToObjectConverter.isValidYaml(payload)) { @@ -150,4 +134,9 @@ public enum PayloadTypeEnum { return Either.right(ActionStatus.INVALID_YAML); } + public abstract Either isValid(byte[] payload); + + public boolean isHeatRelated() { + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java index acf80cb5d0..845487b1ab 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.exceptions; import lombok.AllArgsConstructor; @@ -28,5 +27,4 @@ public class BusinessLogicException extends Exception { @Getter private final ResponseFormat responseFormat; - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java index 788d63819e..e973fe4bf3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java @@ -19,12 +19,11 @@ */ package org.openecomp.sdc.be.components.impl.exceptions; +import java.util.Arrays; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.Arrays; - public class ByActionStatusComponentException extends ComponentException { private final ActionStatus actionStatus; @@ -51,10 +50,6 @@ public class ByActionStatusComponentException extends ComponentException { @Override public String toString() { - return "ComponentException{" + - "actionStatus=" + actionStatus + - ", params=" + Arrays.toString(params) + - '}'; + return "ComponentException{" + "actionStatus=" + actionStatus + ", params=" + Arrays.toString(params) + '}'; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java index 85fe3ec58a..3577b7adef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java @@ -39,7 +39,7 @@ public class ByResponseFormatComponentException extends ComponentException { return params.clone(); } - public ActionStatus getActionStatus(){ + public ActionStatus getActionStatus() { return actionStatus; } @@ -50,9 +50,6 @@ public class ByResponseFormatComponentException extends ComponentException { @Override public String toString() { - return "ComponentException{" + - "responseFormat=" + responseFormat + - '}'; + return "ComponentException{" + "responseFormat=" + responseFormat + '}'; } - } 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 index 1d9809806c..351d279875 100644 --- 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 @@ -17,30 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.exceptions; +import javax.annotation.Nullable; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.exception.ResponseFormat; -import javax.annotation.Nullable; - 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 Resource getResource() { - return resource; - } - private final Resource resource; public ComponentException(ResponseFormat responseFormat) { @@ -62,6 +54,10 @@ public class ComponentException extends RuntimeException { this.resource = resource; } + public Resource getResource() { + return resource; + } + @Nullable public ResponseFormat getResponseFormat() { return responseFormat; @@ -74,6 +70,4 @@ public class ComponentException extends RuntimeException { public String[] getParams() { return params.clone(); } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java index 441e68bb9d..594e3e4ea3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.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. @@ -17,16 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.exceptions; public class SdcResourceNotFoundException extends RuntimeException { - private static final long serialVersionUID = 4431147390120646573L; + private static final long serialVersionUID = 4431147390120646573L; - public SdcResourceNotFoundException(){} + public SdcResourceNotFoundException() { + } - public SdcResourceNotFoundException(String message){ - super(message); - } + public SdcResourceNotFoundException(String message) { + super(message); + } } 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 840fd03e0d..a00f44ce39 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 @@ -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. @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.generic; import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -36,15 +38,10 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - @org.springframework.stereotype.Component public class GenericTypeBusinessLogic { private final static Logger log = Logger.getLogger(GenericTypeBusinessLogic.class); - private final ComponentsUtils componentsUtils; private final ToscaOperationFacade toscaOperationFacade; @@ -58,58 +55,54 @@ public class GenericTypeBusinessLogic { * @param component the component of which to fetch its generic type * @return the generic node type which corresponds to the given component */ - public Either fetchDerivedFromGenericType(Component component){ + public Either fetchDerivedFromGenericType(Component component) { String genericTypeToscaName = getGenericTypeToscaName(component); log.debug("Fetching generic tosca name {}", genericTypeToscaName); - if(null == genericTypeToscaName) { + if (null == genericTypeToscaName) { log.debug("Failed to fetch certified generic node type for component {}", component.getName()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - - Either findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName); - if(findLatestGeneric.isRight()){ + Either findLatestGeneric = toscaOperationFacade + .getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName); + if (findLatestGeneric.isRight()) { log.debug("Failed to fetch certified node type by tosca resource name {}", genericTypeToscaName); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName)); } - Resource genericTypeResource = findLatestGeneric.left().value(); return Either.left(genericTypeResource); } /** - * * @param genericType the generic node type * @return the generic type properties as inputs */ public List generateInputsFromGenericTypeProperties(Resource genericType) { List genericTypeProps = genericType.getProperties(); - if(null != genericTypeProps) { + if (null != genericTypeProps) { return convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericType.getUniqueId()); } return new ArrayList<>(); } public List convertGenericTypePropertiesToInputsDefintion(List genericTypeProps, String genericUniqueId) { - return genericTypeProps.stream() - .map(p -> setInputDefinitionFromProp(p, genericUniqueId)) - .collect(Collectors.toList()); + return genericTypeProps.stream().map(p -> setInputDefinitionFromProp(p, genericUniqueId)).collect(Collectors.toList()); } - private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId){ + private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId) { InputDefinition input = new InputDefinition(prop); input.setOwnerId(genericUniqueId); return input; } private String getGenericTypeToscaName(T component) { - if(component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()){ + if (component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()) { return component.getDerivedFromGenericType(); } - return isCvfcHasDerivedFrom(component) ? ((Resource)component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig(); + return isCvfcHasDerivedFrom(component) ? ((Resource) component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig(); } private boolean isCvfcHasDerivedFrom(T component) { - return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).getResourceType() == ResourceTypeEnum.CVFC && CollectionUtils.isNotEmpty(((Resource)component).getDerivedFrom()); + return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC + && CollectionUtils.isNotEmpty(((Resource) component).getDerivedFrom()); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java index b4df58b46d..74e16a1876 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.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. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.group; -import org.apache.commons.collections.MapUtils; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.springframework.stereotype.Component; +import static org.apache.commons.collections.MapUtils.isEmpty; import java.util.List; import java.util.Map; - -import static org.apache.commons.collections.MapUtils.isEmpty; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.springframework.stereotype.Component; /** * A Helper class which handles altering the members state of a group @@ -69,8 +67,4 @@ public class GroupMembersUpdater { } return invertedMap.get(memberToFind).toString(); } - - - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java index 8e9ba7a88b..29a2d7c88d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java @@ -17,10 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.group; +import static org.apache.commons.collections.CollectionUtils.isEmpty; + import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.version.OnChangeVersionCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -35,63 +39,27 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.utils.GroupUtils; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; - - /** * A Helper class which handles altering the version of a group */ @org.springframework.stereotype.Component public class GroupVersionUpdater implements OnChangeVersionCommand { - + private static final Logger log = Logger.getLogger(GroupVersionUpdater.class); private final GroupsOperation groupsOperation; private final ComponentsUtils componentsUtils; - public GroupVersionUpdater(GroupsOperation groupsOperation, ComponentsUtils componentsUtils) { this.groupsOperation = groupsOperation; this.componentsUtils = componentsUtils; - - } - - - @Override - public ActionStatus onChangeVersion(Component container) { - log.debug("#onChangeVersion - replacing all group members for component instance"); - Consumer> replaceGroupMemberTask = (groups) -> increaseVersion(groups, container); - return updateGroupsVersion(container, replaceGroupMemberTask); - } - - public void increaseVersion(List groups, Component container) { - groups.forEach(group -> increaseMajorVersion(group, container)); - } - - - private void increaseMajorVersion(GroupDefinition group, Component container) { - String version = group.getVersion(); - - String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, group.getVersion()); - - if(!version.equals(newVersion) ){ - if(isGenerateGroupUUID(group, container)) { - String groupUUID = UniqueIdBuilder.generateUUID(); - group.setGroupUUID(groupUUID); - } - group.setVersion(String.valueOf(newVersion)); - } } static List emptyIfNull(final List list) { - return (list == null? Collections.emptyList() : list); + return (list == null ? Collections.emptyList() : list); } static Map emptyIfNull(final Map list) { - return (list == null? Collections.emptyMap() : list); + return (list == null ? Collections.emptyMap() : list); } static boolean isGenerateGroupUUID(GroupDefinition group, Component container) { @@ -100,16 +68,11 @@ public class GroupVersionUpdater implements OnChangeVersionCommand { } else { List artifactsUuid = emptyIfNull(group.getArtifactsUuid()); Map deploymentArtifacts = emptyIfNull(container.getDeploymentArtifacts()); - List heatArtifactUniqueIDs = emptyIfNull(group.getArtifacts()).stream().filter(a -> !a.endsWith("env")).collect( - Collectors.toList()); - + List heatArtifactUniqueIDs = emptyIfNull(group.getArtifacts()).stream().filter(a -> !a.endsWith("env")) + .collect(Collectors.toList()); for (String heatArtifactUniqueID : heatArtifactUniqueIDs) { - ArtifactDefinition artifactDefinition = deploymentArtifacts - .get(heatArtifactUniqueID.split("\\.", -1)[1]); - - if ((artifactDefinition == null - || artifactDefinition.isEmpty()) - || !artifactsUuid.contains(artifactDefinition.getArtifactUUID())) { + ArtifactDefinition artifactDefinition = deploymentArtifacts.get(heatArtifactUniqueID.split("\\.", -1)[1]); + if ((artifactDefinition == null || artifactDefinition.isEmpty()) || !artifactsUuid.contains(artifactDefinition.getArtifactUUID())) { return true; } } @@ -117,6 +80,29 @@ public class GroupVersionUpdater implements OnChangeVersionCommand { } } + @Override + public ActionStatus onChangeVersion(Component container) { + log.debug("#onChangeVersion - replacing all group members for component instance"); + Consumer> replaceGroupMemberTask = (groups) -> increaseVersion(groups, container); + return updateGroupsVersion(container, replaceGroupMemberTask); + } + + public void increaseVersion(List groups, Component container) { + groups.forEach(group -> increaseMajorVersion(group, container)); + } + + private void increaseMajorVersion(GroupDefinition group, Component container) { + String version = group.getVersion(); + String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, group.getVersion()); + if (!version.equals(newVersion)) { + if (isGenerateGroupUUID(group, container)) { + String groupUUID = UniqueIdBuilder.generateUUID(); + group.setGroupUUID(groupUUID); + } + group.setVersion(String.valueOf(newVersion)); + } + } + private ActionStatus updateGroupsVersion(Component groupsContainer, Consumer> updateGroupVersion) { List groups = groupsContainer.getGroups(); if (isEmpty(groups)) { @@ -124,14 +110,10 @@ public class GroupVersionUpdater implements OnChangeVersionCommand { } updateGroupVersion.accept(groups); return updateGroups(groupsContainer.getUniqueId(), groups); - } + } - private ActionStatus updateGroups(String componentId, List groupsToUpdate) { log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), componentId); return componentsUtils.convertFromStorageResponse(groupsOperation.updateGroupsOnComponent(componentId, groupsToUpdate)); - } - } - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java index e631e9f728..fa1211d8ab 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.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. @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.instance; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; 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.common.log.wrappers.Logger; -import java.util.Iterator; -import java.util.List; -import java.util.function.Function; - @org.springframework.stereotype.Component public class ComponentInstanceChangeOperationOrchestrator { @@ -40,24 +38,27 @@ public class ComponentInstanceChangeOperationOrchestrator { } 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()); - Function instanceChangeTaskRunner = operation -> operation.onChangeVersion(container, prevVersion, newVersion); + log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", + container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId()); + Function instanceChangeTaskRunner = operation -> operation + .onChangeVersion(container, prevVersion, newVersion); return doOnChangeInstanceOperations(instanceChangeTaskRunner); } public ActionStatus doOnDeleteInstanceOperations(Component container, String deletedInstanceId) { - log.debug("#doPostChangeVersionOperations - starting on delete instance operations for component {} and instance {}.", container.getUniqueId(), deletedInstanceId); - Function instanceChangeTaskRunner = operation -> operation.onDelete(container, deletedInstanceId); + log.debug("#doPostChangeVersionOperations - starting on delete instance operations for component {} and instance {}.", + container.getUniqueId(), deletedInstanceId); + Function instanceChangeTaskRunner = operation -> operation + .onDelete(container, deletedInstanceId); return doOnChangeInstanceOperations(instanceChangeTaskRunner); } private ActionStatus doOnChangeInstanceOperations(Function instanceChangeTaskRunner) { ActionStatus onDeleteInstanceResult = ActionStatus.OK; Iterator onDeleteInstIter = onInstanceChangeOperations.iterator(); - while(onDeleteInstIter.hasNext() && onDeleteInstanceResult == ActionStatus.OK) { + while (onDeleteInstIter.hasNext() && onDeleteInstanceResult == ActionStatus.OK) { onDeleteInstanceResult = instanceChangeTaskRunner.apply(onDeleteInstIter.next()); } return onDeleteInstanceResult; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java index 656dd2e6e3..7a8f1201de 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.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. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.instance; +import static org.apache.commons.collections.CollectionUtils.isEmpty; + +import java.util.List; +import java.util.function.Consumer; import org.openecomp.sdc.be.components.impl.group.GroupMembersUpdater; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; @@ -30,10 +33,6 @@ import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.List; -import java.util.function.Consumer; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; @org.springframework.stereotype.Component public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOperation { @@ -50,8 +49,10 @@ public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOpe @Override public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { - log.debug("#onChangeVersion - replacing all group members for component instance {} with new component instance on component", prevVersion.getUniqueId(), newVersion.getUniqueId(), container.getUniqueId()); - Consumer> replaceGroupMemberTask = (groups) -> groupMembersUpdater.replaceMember(groups, prevVersion.getUniqueId(), newVersion.getUniqueId()); + log.debug("#onChangeVersion - replacing all group members for component instance {} with new component instance on component", + prevVersion.getUniqueId(), newVersion.getUniqueId(), container.getUniqueId()); + Consumer> replaceGroupMemberTask = (groups) -> groupMembersUpdater + .replaceMember(groups, prevVersion.getUniqueId(), newVersion.getUniqueId()); return doUpdateGroupMembers(container, prevVersion.getUniqueId(), replaceGroupMemberTask); } @@ -75,9 +76,6 @@ public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOpe private ActionStatus updateGroups(Component container, List groupsToUpdate) { log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId()); return groupsOperation.updateGroups(container, groupsToUpdate, PromoteVersionEnum.MINOR) - .either(groupsUpdated -> ActionStatus.OK, - err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType())); + .either(groupsUpdated -> ActionStatus.OK, err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType())); } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java index 173fb3fdbd..5093a153cb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.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. @@ -17,22 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.instance; 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 OnChangeVersionOperation { /** * A side effect operation to execute when a component instance version was changed from {@code prevVersion} to {@code newVersion} - * @param container the container which contains the instance which is version was changed + * + * @param container the container which contains the instance which is version was changed * @param prevVersion the previous version of the component instance. - * @param newVersion the new version of the component instance. + * @param newVersion the new version of the component instance. * @return the status of the operation */ ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java index a01421eadb..f27cf5b031 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.instance; import org.openecomp.sdc.be.components.impl.OnDeleteEntityOperation; @@ -26,4 +25,5 @@ import org.openecomp.sdc.be.components.impl.OnDeleteEntityOperation; * An interface which groups all operations to be executed when an action on a component instance has occurred */ public interface OnComponentInstanceChangeOperation extends OnChangeVersionOperation, OnDeleteEntityOperation { + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java index 863be79d38..7ef9fc77fb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.instance; import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler; @@ -39,8 +38,10 @@ public class PolicyTargetsUpdateOperation implements OnComponentInstanceChangeOp @Override public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { - log.debug("#onChangeVersion - replacing all policy targets referencing component instance {} with component instance {}", prevVersion.getUniqueId(), newVersion.getUniqueId()); - return policyTargetsUpdateHandler.replacePoliciesTargets(container, prevVersion.getUniqueId(), newVersion.getUniqueId(), PolicyTargetType.COMPONENT_INSTANCES); + log.debug("#onChangeVersion - replacing all policy targets referencing component instance {} with component instance {}", + prevVersion.getUniqueId(), newVersion.getUniqueId()); + return policyTargetsUpdateHandler + .replacePoliciesTargets(container, prevVersion.getUniqueId(), newVersion.getUniqueId(), PolicyTargetType.COMPONENT_INSTANCES); } @Override @@ -48,6 +49,4 @@ public class PolicyTargetsUpdateOperation implements OnComponentInstanceChangeOp log.debug("#onDelete - removing all component {} policy targets referencing component instance {}", container.getUniqueId(), deletedEntityId); return policyTargetsUpdateHandler.removePoliciesTargets(container, deletedEntityId, PolicyTargetType.COMPONENT_INSTANCES); } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java index 892ea8cfd4..cfd0675f58 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.lock; import org.aspectj.lang.ProceedingJoinPoint; @@ -46,13 +45,10 @@ public class ComponentLockAspect { componentLocker.lock(componentId, componentType); log.trace("#{} - after locking component {} of type {}", methodName, componentId, componentType); return proceedingJoinPoint.proceed(); - } - finally { + } finally { log.trace("#{} - before unlocking component {} of type {}", methodName, componentId, componentType); componentLocker.unlock(componentId, componentType); log.trace("#{} - after unlocking component {} of type {}", methodName, componentId, componentType); } } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java index 44e49eb039..9a0d2517d8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.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. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.lock; -import org.springframework.transaction.annotation.Transactional; - 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; +import org.springframework.transaction.annotation.Transactional; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java index 00f5fd8ab1..a5416dd73d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.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. @@ -17,12 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.model; -import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata; - import java.util.Map; +import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata; public class ToscaTypeImportData { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java index 3b3dab34a6..df2ea21857 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.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. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.policy; +import static org.apache.commons.collections.CollectionUtils.isEmpty; + +import java.util.List; +import java.util.function.Consumer; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -29,11 +32,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.List; -import java.util.function.Consumer; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; - @org.springframework.stereotype.Component public class PolicyTargetsUpdateHandler { @@ -42,7 +40,8 @@ public class PolicyTargetsUpdateHandler { private final ComponentsUtils componentsUtils; private final PolicyTargetsUpdater policyTargetsUpdater; - public PolicyTargetsUpdateHandler(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, PolicyTargetsUpdater policyTargetsUpdater) { + public PolicyTargetsUpdateHandler(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, + PolicyTargetsUpdater policyTargetsUpdater) { this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; this.policyTargetsUpdater = policyTargetsUpdater; @@ -56,11 +55,13 @@ public class PolicyTargetsUpdateHandler { public ActionStatus replacePoliciesTargets(Component container, String prevTargetId, String newTargetId, PolicyTargetType targetType) { log.debug("#replacePoliciesTargets - replacing all policy targets referencing target {} with target {}", prevTargetId, newTargetId); - Consumer> replaceTarget = policies -> policyTargetsUpdater.replaceTarget(policies, prevTargetId, newTargetId, targetType); + Consumer> replaceTarget = policies -> policyTargetsUpdater + .replaceTarget(policies, prevTargetId, newTargetId, targetType); return updatePolicyTargets(container, prevTargetId, targetType, replaceTarget); } - private ActionStatus updatePolicyTargets(Component container, String targetId, PolicyTargetType targetType, Consumer> updatePolicyTargetTaskRunner) { + private ActionStatus updatePolicyTargets(Component container, String targetId, PolicyTargetType targetType, + Consumer> updatePolicyTargetTaskRunner) { List policiesWithPrevInstanceAsTarget = container.resolvePoliciesContainingTarget(targetId, targetType); if (isEmpty(policiesWithPrevInstanceAsTarget)) { return ActionStatus.OK; @@ -74,5 +75,4 @@ public class PolicyTargetsUpdateHandler { StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate); return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType()); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java index adf927178f..e2d5f546da 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.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. @@ -17,9 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.policy; +import static java.util.Collections.emptyList; +import static org.apache.commons.collections.CollectionUtils.isEmpty; + +import java.util.List; +import java.util.Map; +import java.util.function.UnaryOperator; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; @@ -27,13 +32,6 @@ import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.utils.GroupUtils; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Map; -import java.util.function.UnaryOperator; - -import static java.util.Collections.emptyList; -import static org.apache.commons.collections.CollectionUtils.isEmpty; - /** * A Helper class which handles altering the targets state of a policy */ @@ -41,7 +39,7 @@ import static org.apache.commons.collections.CollectionUtils.isEmpty; public class PolicyTargetsUpdater { public void removeTarget(List policies, String targetId, PolicyTargetType targetType) { - policies.forEach(policy ->removePolicyTarget(policy, targetId, targetType)); + policies.forEach(policy -> removePolicyTarget(policy, targetId, targetType)); } public void replaceTarget(List policies, String oldTargetId, String newTargetId, PolicyTargetType targetType) { @@ -62,21 +60,19 @@ public class PolicyTargetsUpdater { if (isEmpty(policyTargets)) { return; } - policyTargets.remove(targetId); policy.setVersion(GroupUtils.updateVersion(PromoteVersionEnum.MINOR, policy.getVersion())); } private List getTargetsList(PolicyDefinition policyDefinition, PolicyTargetType targetType) { Map> targets = policyDefinition.getTargets(); - if(MapUtils.isEmpty(targets) || isEmpty(targets.get(targetType))) { + if (MapUtils.isEmpty(targets) || isEmpty(targets.get(targetType))) { return emptyList(); } return targets.get(targetType); } private UnaryOperator prevInstanceIdByNewInstanceId(String prevInstanceId, String newInstanceId) { - return instId -> instId.equals(prevInstanceId) ? newInstanceId: instId; + return instId -> instId.equals(prevInstanceId) ? newInstanceId : instId; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java index ef2f8cbad9..ac6e89d6a1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.policy; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import java.util.List; +import java.util.function.Consumer; import org.openecomp.sdc.be.components.impl.version.OnChangeVersionCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; @@ -33,30 +35,21 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.utils.GroupUtils; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.List; -import java.util.function.Consumer; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; - - /** * A Helper class which handles altering the version of a group */ @org.springframework.stereotype.Component public class PolicyVersionUpdater implements OnChangeVersionCommand { - + private static final Logger log = Logger.getLogger(PolicyVersionUpdater.class); private final ToscaOperationFacade toscaOperationFacade; private final ComponentsUtils componentsUtils; - public PolicyVersionUpdater(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; - } - - + @Override public ActionStatus onChangeVersion(Component container) { log.debug("#onChangeVersion - replacing all group members for component instance"); @@ -68,21 +61,16 @@ public class PolicyVersionUpdater implements OnChangeVersionCommand { policies.forEach(policy -> increaseMajorVersion(policy)); } - private void increaseMajorVersion(PolicyDefinition policy) { String version = policy.getVersion(); - String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, policy.getVersion()); - - if(!version.equals(newVersion) ){ + if (!version.equals(newVersion)) { String groupUUID = UniqueIdBuilder.generateUUID(); policy.setPolicyUUID(groupUUID); policy.setVersion(String.valueOf(newVersion)); } + } - } - - private ActionStatus updatePoliciesVersion(Component container, Consumer> updatePoliciesVersion) { List policies = container.resolvePoliciesList(); if (isEmpty(policies)) { @@ -90,15 +78,11 @@ public class PolicyVersionUpdater implements OnChangeVersionCommand { } updatePoliciesVersion.accept(policies); return updatePolicies(container, policies); - } + } - 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()); } - } - - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java index 36c1e585d8..a7dd5afc10 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.impl.utils; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterCapabilityDataDefinition; @@ -25,22 +27,15 @@ import org.openecomp.sdc.be.model.UploadNodeFilterInfo; import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - public class CINodeFilterUtils { Logger log = Logger.getLogger(CINodeFilterUtils.class); - - public CINodeFilterDataDefinition getNodeFilterDataDefinition( - UploadNodeFilterInfo uploadNodeFilterInfo, String uniqueId) { - CINodeFilterDataDefinition nodeFilterDataDefinition = - new CINodeFilterDataDefinition(); + public CINodeFilterDataDefinition getNodeFilterDataDefinition(UploadNodeFilterInfo uploadNodeFilterInfo, String uniqueId) { + CINodeFilterDataDefinition nodeFilterDataDefinition = new CINodeFilterDataDefinition(); nodeFilterDataDefinition.setName(uploadNodeFilterInfo.getName()); - List collect = - uploadNodeFilterInfo.getProperties().stream().map(this::buildProperty).collect(Collectors.toList()); + List collect = uploadNodeFilterInfo.getProperties().stream().map(this::buildProperty) + .collect(Collectors.toList()); ListDataDefinition listDataDefinition = new ListDataDefinition<>(); listDataDefinition.getListToscaDataDefinition().addAll(collect); nodeFilterDataDefinition.setProperties(listDataDefinition); @@ -51,38 +46,31 @@ public class CINodeFilterUtils { } private ListDataDefinition converCapabilties( - Map capabilities) { - ListDataDefinition listDataDefinition = - new ListDataDefinition<>(); + Map capabilities) { + ListDataDefinition listDataDefinition = new ListDataDefinition<>(); for (UploadNodeFilterCapabilitiesInfo capability : capabilities.values()) { - RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition = - convertCapability(capability); + RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition = convertCapability(capability); listDataDefinition.add(requirementNodeFilterCapabilityDataDefinition); } return listDataDefinition; } - private RequirementNodeFilterCapabilityDataDefinition convertCapability( - UploadNodeFilterCapabilitiesInfo capability) { + private RequirementNodeFilterCapabilityDataDefinition convertCapability(UploadNodeFilterCapabilitiesInfo capability) { RequirementNodeFilterCapabilityDataDefinition retVal = new RequirementNodeFilterCapabilityDataDefinition(); retVal.setName(capability.getName()); - List props = - capability.getProperties().stream().map(this::buildProperty).collect(Collectors.toList()); + List props = capability.getProperties().stream().map(this::buildProperty) + .collect(Collectors.toList()); ListDataDefinition propsList = new ListDataDefinition<>(); propsList.getListToscaDataDefinition().addAll(props); retVal.setProperties(propsList); return retVal; } - - private RequirementNodeFilterPropertyDataDefinition buildProperty( - UploadNodeFilterPropertyInfo uploadNodeFilterPropertyInfo) { + private RequirementNodeFilterPropertyDataDefinition buildProperty(UploadNodeFilterPropertyInfo uploadNodeFilterPropertyInfo) { RequirementNodeFilterPropertyDataDefinition retVal = new RequirementNodeFilterPropertyDataDefinition(); retVal.setName(uploadNodeFilterPropertyInfo.getName()); List propertyConstraints = uploadNodeFilterPropertyInfo.getValues(); retVal.setConstraints(propertyConstraints); return retVal; } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java index 20a294c076..8deebb60b8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.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. @@ -17,12 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.utils; -import org.openecomp.sdc.be.model.CapabilityTypeDefinition; - import java.util.Objects; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; public class CapabilityTypeImportUtils { @@ -33,16 +31,14 @@ public class CapabilityTypeImportUtils { if (capabilityType1 == capabilityType2) { return true; } - if (capabilityType1 == null || capabilityType2 == null) { return false; } - - return Objects.equals(capabilityType1.getType(), capabilityType2.getType()) && - Objects.equals(capabilityType1.getVersion(), capabilityType2.getVersion()) && - Objects.equals(capabilityType1.getDerivedFrom(), capabilityType2.getDerivedFrom()) && - Objects.equals(capabilityType1.getValidSourceTypes(), capabilityType2.getValidSourceTypes()) && - Objects.equals(capabilityType1.getDescription(), capabilityType2.getDescription()) && - Objects.equals(capabilityType1.getProperties(), capabilityType2.getProperties()); + return Objects.equals(capabilityType1.getType(), capabilityType2.getType()) && Objects + .equals(capabilityType1.getVersion(), capabilityType2.getVersion()) && Objects + .equals(capabilityType1.getDerivedFrom(), capabilityType2.getDerivedFrom()) && Objects + .equals(capabilityType1.getValidSourceTypes(), capabilityType2.getValidSourceTypes()) && Objects + .equals(capabilityType1.getDescription(), capabilityType2.getDescription()) && Objects + .equals(capabilityType1.getProperties(), capabilityType2.getProperties()); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java index 02176d902b..038df27939 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.utils; import java.util.List; @@ -37,46 +36,28 @@ public final class ComponentUtils { private ComponentUtils() { } - public static boolean checkArtifactInComponent( - Component component, String artifactId - ) { - Predicate hasSameArtifactId = - ad -> ad != null && ad.getUniqueId().equals(artifactId); - - return exists(component.getArtifacts(), hasSameArtifactId) || - exists(component.getDeploymentArtifacts(), hasSameArtifactId) || - exists(component.getToscaArtifacts(), hasSameArtifactId) || - hasOperationImplementationWithUniqueId(component, artifactId) || - isServiceAndHasApiArtifactWithUniqueId(component, hasSameArtifactId); + public static boolean checkArtifactInComponent(Component component, String artifactId) { + Predicate hasSameArtifactId = ad -> ad != null && ad.getUniqueId().equals(artifactId); + return exists(component.getArtifacts(), hasSameArtifactId) || exists(component.getDeploymentArtifacts(), hasSameArtifactId) || exists( + component.getToscaArtifacts(), hasSameArtifactId) || hasOperationImplementationWithUniqueId(component, artifactId) + || isServiceAndHasApiArtifactWithUniqueId(component, hasSameArtifactId); } - private static boolean isServiceAndHasApiArtifactWithUniqueId(Component component, - Predicate hasSameArtifactId) { - return component.getComponentType() == ComponentTypeEnum.SERVICE && exists( - ((Service) component).getServiceApiArtifacts(), hasSameArtifactId); + private static boolean isServiceAndHasApiArtifactWithUniqueId(Component component, Predicate hasSameArtifactId) { + return component.getComponentType() == ComponentTypeEnum.SERVICE && exists(((Service) component).getServiceApiArtifacts(), hasSameArtifactId); } private static boolean hasOperationImplementationWithUniqueId(Component component, String artifactId) { - return findFirst(valueStream(component.getInterfaces()) - .flatMap(v -> valueStream(v.getOperationsMap())) - .map(OperationDataDefinition::getImplementation), - e -> e != null && e.getUniqueId().equals(artifactId) - ).isPresent(); + return findFirst( + valueStream(component.getInterfaces()).flatMap(v -> valueStream(v.getOperationsMap())).map(OperationDataDefinition::getImplementation), + e -> e != null && e.getUniqueId().equals(artifactId)).isPresent(); } - public static boolean checkArtifactInResourceInstance( - Component component, String resourceInstanceId, String artifactId - ) { - Predicate hasSameResourceId = - ri -> ri != null && ri.getUniqueId().equals(resourceInstanceId); - - Predicate hasSameArtifactId = - ad -> ad != null && ad.getUniqueId().equals(artifactId); - - return findFirst(component.getComponentInstances(), hasSameResourceId).map(ri -> - exists(ri.getDeploymentArtifacts(), hasSameArtifactId) || - exists(ri.getArtifacts(), hasSameArtifactId) - ).isPresent(); + public static boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) { + Predicate hasSameResourceId = ri -> ri != null && ri.getUniqueId().equals(resourceInstanceId); + Predicate hasSameArtifactId = ad -> ad != null && ad.getUniqueId().equals(artifactId); + return findFirst(component.getComponentInstances(), hasSameResourceId) + .map(ri -> exists(ri.getDeploymentArtifacts(), hasSameArtifactId) || exists(ri.getArtifacts(), hasSameArtifactId)).isPresent(); } private static Optional findFirst(List ovs, Predicate p) { @@ -84,9 +65,7 @@ public final class ComponentUtils { } private static boolean exists(Map okvs, Predicate p) { - return Optional.ofNullable(okvs) - .flatMap(kvs -> findFirst(kvs.values().stream(), p)) - .isPresent(); + return Optional.ofNullable(okvs).flatMap(kvs -> findFirst(kvs.values().stream(), p)).isPresent(); } private static Optional findFirst(Stream vs, Predicate p) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java index 5d2f26a991..b0ad5ef9ee 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.impl.utils; +import java.util.List; +import java.util.Map; import lombok.Getter; import lombok.Setter; import org.openecomp.sdc.be.components.csar.CsarInfo; @@ -23,11 +24,10 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.NodeTypeInfo; import org.openecomp.sdc.be.model.ParsedToscaYamlInfo; -import java.util.List; -import java.util.Map; @Getter @Setter public class CreateServiceFromYamlParameter { + private String yamlName; private ParsedToscaYamlInfo parsedToscaYamlInfo; private List createdArtifacts; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java index eb7e6baaf3..c759440b4f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.utils; import java.util.List; @@ -29,9 +28,7 @@ public class DirectivesUtil { private static Optional getDirective(final String directiveValue) { final List directives = ConfigurationManager.getConfigurationManager().getConfiguration().getDirectives(); if (CollectionUtils.isNotEmpty(directives)) { - return directives.stream() - .filter(directiveValues -> directiveValues.equalsIgnoreCase(directiveValue)) - .findFirst(); + return directives.stream().filter(directiveValues -> directiveValues.equalsIgnoreCase(directiveValue)).findFirst(); } return Optional.empty(); } @@ -42,5 +39,4 @@ public class DirectivesUtil { } return inDirectives.stream().allMatch(directive -> getDirective(directive).isPresent()); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java index ec4192c966..316b82b94e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java @@ -40,27 +40,23 @@ public class ExceptionUtils { this.janusGraphDao = janusGraphDao; } - public T rollBackAndThrow(ActionStatus actionStatus, String ... params) { - janusGraphDao.rollback(); - throw new ByActionStatusComponentException(actionStatus, params); - } + public T rollBackAndThrow(ActionStatus actionStatus, String... params) { + janusGraphDao.rollback(); + throw new ByActionStatusComponentException(actionStatus, params); + } public T rollBackAndThrow(ResponseFormat responseFormat) { janusGraphDao.rollback(); throw new ByResponseFormatComponentException(responseFormat); } - public T rollBackAndThrow(StorageOperationStatus status, String ... params) { + public T rollBackAndThrow(StorageOperationStatus status, String... params) { janusGraphDao.rollback(); throw new StorageException(status, params); } - public T rollBackAndThrow(JanusGraphOperationStatus status, String ... params) { + public T rollBackAndThrow(JanusGraphOperationStatus status, String... params) { janusGraphDao.rollback(); throw new StorageException(status, params); } - - - - } 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 index 4516a226d4..e8ba2d1a2f 100644 --- 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 @@ -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. @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.utils; -import org.openecomp.sdc.be.dao.utils.MapUtil; -import org.openecomp.sdc.be.model.PolicyTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.springframework.util.CollectionUtils.isEmpty; import java.util.List; import java.util.Map; import java.util.Objects; - -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.springframework.util.CollectionUtils.isEmpty; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; public class PolicyTypeImportUtils { @@ -43,22 +41,15 @@ public class PolicyTypeImportUtils { if (pt1 == null || pt2 == null) { return false; } - return Objects.equals(pt1.getType(), pt2.getType()) && - Objects.equals(pt1.getName(), pt2.getName()) && - Objects.equals(pt1.getIcon(), pt2.getIcon()) && - 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()); + return Objects.equals(pt1.getType(), pt2.getType()) && Objects.equals(pt1.getName(), pt2.getName()) && Objects + .equals(pt1.getIcon(), pt2.getIcon()) && 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) - || pt1Props == null && isEmpty(pt2Props) - || pt2Props == null && isEmpty(pt1Props)) { + private static boolean isPolicyPropertiesEquals(List pt1Props, List pt2Props) { + if ((pt1Props == pt2Props) || pt1Props == null && isEmpty(pt2Props) || pt2Props == null && isEmpty(pt1Props)) { return true; } else if (!isPropertiesListSizesEquals(pt1Props, pt2Props)) { return false; @@ -66,8 +57,8 @@ public class PolicyTypeImportUtils { // The two cases tested by these assertions should have been taken care of by the previous two tests assert (pt1Props != null && pt2Props != null); Map pt1PropsByName = MapUtil.toMap(pt1Props, PropertyDefinition::getName); - long numberOfEqualsProperties = pt2Props.stream() - .filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop)).count(); + long numberOfEqualsProperties = pt2Props.stream().filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop)) + .count(); return numberOfEqualsProperties == pt1Props.size(); } } @@ -79,17 +70,13 @@ public class PolicyTypeImportUtils { 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()); + 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 isPropertiesListSizesEquals(List pt1Props, List pt2Props) { - return (isEmpty(pt1Props) && isEmpty(pt2Props)) - || (isNotEmpty(pt1Props) && isNotEmpty(pt2Props) && pt1Props.size() == pt2Props.size()); + return (isEmpty(pt1Props) && isEmpty(pt2Props)) || (isNotEmpty(pt1Props) && isNotEmpty(pt2Props) && pt1Props.size() == pt2Props.size()); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java index eee84bb14b..d7f92929cb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java @@ -40,8 +40,7 @@ public class PMDictionaryValidator { public Optional validateIfPmDictionary(String artifactType, byte[] decodedPayload) { if (isPmDictionary(artifactType)) { - return validate(decodedPayload).stream() - .reduce((a, b) -> a + "; " + b); + return validate(decodedPayload).stream().reduce((a, b) -> a + "; " + b); } return Optional.empty(); } @@ -54,9 +53,7 @@ public class PMDictionaryValidator { List errors = new ArrayList<>(); try { List validationErrors = yamlContentValidator.validate(fileContent); - validationErrors.stream() - .map(this::formatErrorMessage) - .forEach(errors::add); + validationErrors.stream().map(this::formatErrorMessage).forEach(errors::add); } catch (Exception e) { errors.add(e.getMessage()); } @@ -64,10 +61,6 @@ public class PMDictionaryValidator { } private String formatErrorMessage(YamlDocumentValidationError error) { - return String.format("Document number: %d, Path: %s, Message: %s", - error.getYamlDocumentNumber(), - error.getPath(), - error.getMessage()); + return String.format("Document number: %d, Path: %s, Message: %s", error.getYamlDocumentNumber(), error.getPath(), error.getMessage()); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java index de115b5099..19cc14ed0d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java @@ -17,23 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.impl.version; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Component; - @FunctionalInterface public interface OnChangeVersionCommand { - + /** * A side effect operation to execute when a component instance version was changed from {@code prevVersion} to {@code newVersion} - * @param container the container which contains the instance which is version was changed + * + * @param container the container which contains the instance which is version was changed * @param prevVersion the previous version of the component instance. - * @param newVersion the new version of the component instance. + * @param newVersion the new version of the component instance. * @return the status of the operation */ ActionStatus onChangeVersion(Component container); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java index 13086c7884..a6bc4d0081 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java @@ -17,50 +17,38 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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.common.log.wrappers.Logger; - import java.util.Iterator; import java.util.List; import java.util.function.Function; - - - +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.common.log.wrappers.Logger; @org.springframework.stereotype.Component public class VesionUpdateHandler { - - private static final Logger log = Logger.getLogger(VesionUpdateHandler.class); + private static final Logger log = Logger.getLogger(VesionUpdateHandler.class); private final List onChangeVersionOperations; - - public VesionUpdateHandler( List onChangeVersionOperations) { - + + public VesionUpdateHandler(List onChangeVersionOperations) { this.onChangeVersionOperations = onChangeVersionOperations; } - - + public ActionStatus doPostChangeVersionCommand(Component container) { - log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId()); + log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", + container.getUniqueId()); Function vesionChangeTaskRunner = operation -> operation.onChangeVersion(container); return doOnChangeVesionOperations(vesionChangeTaskRunner); } - + private ActionStatus doOnChangeVesionOperations(Function vesionChangeTaskRunner) { ActionStatus onVesionChangeResult = ActionStatus.OK; Iterator onChangeVesionIter = onChangeVersionOperations.iterator(); - while(onChangeVesionIter.hasNext() && onVesionChangeResult == ActionStatus.OK) { + while (onChangeVesionIter.hasNext() && onVesionChangeResult == ActionStatus.OK) { onVesionChangeResult = vesionChangeTaskRunner.apply(onChangeVesionIter.next()); } return onVesionChangeResult; } - - - - - } 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 7adc77f1b2..757c789d5c 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 @@ -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. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.lifecycle; import fj.data.Either; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; @@ -52,38 +55,31 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; - public class CertificationChangeTransition extends LifeCycleTransition { - private static final String ALLOTTED_CATEGORY = "Allotted Resource"; - private static final String DEPENDING_SRV_NAME = "depending_service_name"; - private static final String PROVIDING_SRV_NAME = "providing_service_name"; - private static final String PROVIDING_SRV_UUID = "providing_service_uuid"; - private static final String DEPENDING_SRV_UUID = "depending_service_uuid"; + private static final String ALLOTTED_CATEGORY = "Allotted Resource"; + private static final String DEPENDING_SRV_NAME = "depending_service_name"; + private static final String PROVIDING_SRV_NAME = "providing_service_name"; + private static final String PROVIDING_SRV_UUID = "providing_service_uuid"; + private static final String DEPENDING_SRV_UUID = "depending_service_uuid"; private static final Logger log = Logger.getLogger(CertificationChangeTransition.class); - private LifecycleStateEnum nextState; private LifeCycleTransitionEnum name; private AuditingActionEnum auditingAction; private NodeTemplateOperation nodeTemplateOperation; private ServiceBusinessLogic serviceBusinessLogic; - public CertificationChangeTransition(ServiceBusinessLogic serviceBusinessLogic, LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + public CertificationChangeTransition(ServiceBusinessLogic serviceBusinessLogic, LifeCycleTransitionEnum name, ComponentsUtils componentUtils, + ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, + JanusGraphDao janusGraphDao) { super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); - this.name = name; this.serviceBusinessLogic = serviceBusinessLogic; - // authorized roles - Role[] certificationChangeRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] resourceRoles = { Role.ADMIN, Role.DESIGNER}; + Role[] certificationChangeRoles = {Role.ADMIN, Role.DESIGNER}; + Role[] resourceRoles = {Role.ADMIN, Role.DESIGNER}; addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceRoles)); addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles)); - this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE; this.nextState = LifecycleStateEnum.CERTIFIED; } @@ -109,57 +105,50 @@ public class CertificationChangeTransition extends LifeCycleTransition { 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"); - return componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(response), component, componentType); } @Override - public 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, 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); + Either userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo); if (userValidationResponse.isRight()) { log.debug("userRoleValidation failed"); return userValidationResponse; } - if (oldState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT && oldState != LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) { log.debug("Valid states for certification are NOT_CERTIFIED_CHECKIN and NOT_CERTIFIED_CHECKOUT. {} is invalid state", oldState); - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, componentName, componentType.name().toLowerCase(), oldState.name()); + ResponseFormat error = componentUtils + .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, componentName, componentType.name().toLowerCase(), oldState.name()); 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 - ) { - + 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 { handleValidationsAndArtifactsGenerationBeforeCertifying(componentType, component, componentBl, modifier, shouldLock, inTransaction); - Either certificationChangeResult = - lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - + Either certificationChangeResult = lifeCycleOperation + .certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); if (certificationChangeResult.isRight()) { ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType); result = Either.right(responseFormat); return result; } - ToscaElement certificationResult = certificationChangeResult.left().value(); T componentAfterCertification = ModelConverter.convertFromToscaElement(certificationResult); - if ( result == null || result.isLeft() ){ + if (result == null || result.isLeft()) { //update edges for allotted resource StorageOperationStatus status = handleConnectionsForAllotted(componentAfterCertification); - if ( status != StorageOperationStatus.OK){ + if (status != StorageOperationStatus.OK) { ResponseFormat responseFormat = formatCertificationError(componentAfterCertification, status, componentType); result = Either.right(responseFormat); } @@ -171,59 +160,55 @@ public class CertificationChangeTransition extends LifeCycleTransition { } finally { if (result == null || result.isRight()) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if ( !inTransaction ) { + if (!inTransaction) { log.debug("operation failed. do rollback"); janusGraphDao.rollback(); } } else { - if ( !inTransaction ) { + if (!inTransaction) { log.debug("operation success. do commit"); janusGraphDao.commit(); } } } - } private void updateCapReqPropertiesOwnerId(Component component) { - if(component.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(component)) { + if (component.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(component)) { toscaOperationFacade.updateCapReqPropertiesOwnerId(component.getUniqueId()); } } Either validateAllResourceInstanceCertified(Component component) { Either eitherResult = Either.left(true); - - if (component.isVspArchived()){ - return Either.right(componentUtils.getResponseFormat(ActionStatus.ARCHIVED_ORIGINS_FOUND, component.getComponentType().name(), component.getName())); + if (component.isVspArchived()) { + return Either.right( + componentUtils.getResponseFormat(ActionStatus.ARCHIVED_ORIGINS_FOUND, component.getComponentType().name(), component.getName())); } - List resourceInstance = component.getComponentInstances(); if (resourceInstance != null) { - //Filter components instances with archived origins - Optional archivedRIOptional = resourceInstance.stream().filter(ComponentInstanceDataDefinition::isOriginArchived).findAny(); - + Optional archivedRIOptional = resourceInstance.stream().filter(ComponentInstanceDataDefinition::isOriginArchived) + .findAny(); //RIs with archived origins found, return relevant error - if (archivedRIOptional.isPresent()){ - return Either.right(componentUtils.getResponseFormat(ActionStatus.ARCHIVED_ORIGINS_FOUND, component.getComponentType().name(), component.getName())); + if (archivedRIOptional.isPresent()) { + return Either.right( + componentUtils.getResponseFormat(ActionStatus.ARCHIVED_ORIGINS_FOUND, component.getComponentType().name(), component.getName())); } - //Continue with searching for non certified RIs - Optional nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny(); + 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) { - Either eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid()); if (eitherResource.isRight()) { return componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); @@ -231,7 +216,6 @@ public class CertificationChangeTransition extends LifeCycleTransition { 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; @@ -248,7 +232,9 @@ public class CertificationChangeTransition extends LifeCycleTransition { return componentUtils.getResponseFormat(actionStatus, componentType == ComponentTypeEnum.RESOURCE ? "VF" : "service", resource.getName()); } - private void handleValidationsAndArtifactsGenerationBeforeCertifying(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, boolean shouldLock, boolean inTransaction) { + private void handleValidationsAndArtifactsGenerationBeforeCertifying(ComponentTypeEnum componentType, Component component, + ComponentBusinessLogic componentBl, User modifier, boolean shouldLock, + boolean inTransaction) { if (component.isTopologyTemplate()) { Either statusCert = validateAllResourceInstanceCertified(component); if (statusCert.isRight()) { @@ -256,37 +242,35 @@ public class CertificationChangeTransition extends LifeCycleTransition { } } if (componentType == ComponentTypeEnum.SERVICE) { - - Either generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock, inTransaction); - + Either generateHeatEnvResult = serviceBusinessLogic + .generateHeatEnvArtifacts((Service) component, modifier, shouldLock, inTransaction); if (generateHeatEnvResult.isRight()) { throw new ByResponseFormatComponentException(generateHeatEnvResult.right().value()); } - Either generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts(generateHeatEnvResult.left().value(), modifier, shouldLock, inTransaction); + Either generateVfModuleResult = serviceBusinessLogic + .generateVfModuleArtifacts(generateHeatEnvResult.left().value(), modifier, shouldLock, inTransaction); if (generateVfModuleResult.isRight()) { throw new ByResponseFormatComponentException(generateVfModuleResult.right().value()); } component = generateVfModuleResult.left().value(); } - componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock); } - private void updateCalculatedCapabilitiesRequirements(Component certifiedComponent) { - if(certifiedComponent.getComponentType() == ComponentTypeEnum.SERVICE){ + if (certifiedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { toscaOperationFacade.updateNamesOfCalculatedCapabilitiesRequirements(certifiedComponent.getUniqueId()); } } - private StorageOperationStatus handleConnectionsForAllotted(Component component){ + private StorageOperationStatus handleConnectionsForAllotted(Component component) { StorageOperationStatus status = StorageOperationStatus.OK; - if (component.getComponentType() == ComponentTypeEnum.RESOURCE && component.isTopologyTemplate() ){ + if (component.getComponentType() == ComponentTypeEnum.RESOURCE && component.isTopologyTemplate()) { List categories = component.getCategories(); - Optional findFirst = categories.stream().filter(c->c.getName().equals(ALLOTTED_CATEGORY)).findFirst(); - if ( findFirst.isPresent() ){ + Optional findFirst = categories.stream().filter(c -> c.getName().equals(ALLOTTED_CATEGORY)).findFirst(); + if (findFirst.isPresent()) { findInstanceByAllottedProperties(component); - }else{ + } else { log.debug("Component isn't from allotted category."); } } @@ -297,27 +281,29 @@ public class CertificationChangeTransition extends LifeCycleTransition { log.debug("Component is from alloted category. Remove all previous ALLOTTED_OF connections for all instances"); nodeTemplateOperation.removeAllAllotedEdges(component.getUniqueId()); Map> componentInstancesProperties = component.getComponentInstancesProperties(); - if ( componentInstancesProperties != null ){ - componentInstancesProperties.entrySet().forEach(e->{ + if (componentInstancesProperties != null) { + componentInstancesProperties.entrySet().forEach(e -> { List props = e.getValue(); - Optional findProp = props.stream().filter(p -> p.getName().equals(DEPENDING_SRV_NAME) || p.getName().equals(PROVIDING_SRV_NAME)).findFirst(); - if ( findProp.isPresent() ){ - log.debug("Find specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME,PROVIDING_SRV_NAME, e.getKey() ); - handleAllotedInstance(component.getUniqueId(), e.getKey(), e.getValue() ); - }else{ - log.debug("Not defined specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME,PROVIDING_SRV_NAME, e.getKey() ); + Optional findProp = props.stream() + .filter(p -> p.getName().equals(DEPENDING_SRV_NAME) || p.getName().equals(PROVIDING_SRV_NAME)).findFirst(); + if (findProp.isPresent()) { + log.debug("Find specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME, PROVIDING_SRV_NAME, e.getKey()); + handleAllotedInstance(component.getUniqueId(), e.getKey(), e.getValue()); + } else { + log.debug("Not defined specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME, PROVIDING_SRV_NAME, e.getKey()); } }); } } private StorageOperationStatus handleAllotedInstance(String componentId, String instanceId, List props) { - ComponentInstanceProperty serviceUUIDProp = props.stream().filter(p -> p.getName().equals(PROVIDING_SRV_UUID) || p.getName().equals(DEPENDING_SRV_UUID)).findFirst().get(); - if ( serviceUUIDProp.getValue() != null && !serviceUUIDProp.getValue().contains("get_input")){ - log.debug("Handle Allotted edge on instance {} for service UUID {} ", instanceId, serviceUUIDProp.getValue() ); - return nodeTemplateOperation.createAllottedOfEdge(componentId, instanceId, serviceUUIDProp.getValue()); - }else{ - log.debug("An incorrectly defined service UUID for Allotted instance {} . Skip instance", instanceId, serviceUUIDProp.getValue() ); + ComponentInstanceProperty serviceUUIDProp = props.stream() + .filter(p -> p.getName().equals(PROVIDING_SRV_UUID) || p.getName().equals(DEPENDING_SRV_UUID)).findFirst().get(); + if (serviceUUIDProp.getValue() != null && !serviceUUIDProp.getValue().contains("get_input")) { + log.debug("Handle Allotted edge on instance {} for service UUID {} ", instanceId, serviceUUIDProp.getValue()); + return nodeTemplateOperation.createAllottedOfEdge(componentId, instanceId, serviceUUIDProp.getValue()); + } else { + log.debug("An incorrectly defined service UUID for Allotted instance {} . Skip instance", instanceId, serviceUUIDProp.getValue()); return StorageOperationStatus.OK; } } 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 db4bef40b1..71c41caf3a 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 @@ -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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.lifecycle; import fj.data.Either; +import java.util.Arrays; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.version.VesionUpdateHandler; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -44,24 +44,21 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.Arrays; - public class CheckinTransition extends LifeCycleTransition { private static final Logger log = Logger.getLogger(CheckinTransition.class); - private VesionUpdateHandler vesionUpdateHandler; - public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao, VesionUpdateHandler groupUpdateHandler) { + public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, + ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao, VesionUpdateHandler groupUpdateHandler) { super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); this.vesionUpdateHandler = groupUpdateHandler; // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + 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 @@ -75,32 +72,28 @@ public class CheckinTransition extends LifeCycleTransition { } @Override - public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + 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()); - + 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.right(responseFormat); + } else { updateCalculatedCapabilitiesRequirements(checkinResourceResult.left().value()); Component r = ModelConverter.convertFromToscaElement(checkinResourceResult.left().value()); updateGroupsAndPolicesVersion(r); - result = Either.left(r); - - + result = Either.left(r); } } finally { if (result == null || result.isRight()) { @@ -124,35 +117,37 @@ public class CheckinTransition extends LifeCycleTransition { } @Override - public 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, 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); + Either userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo); if (userValidationResponse.isRight()) { return userValidationResponse; } - if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN; - if (oldState.equals(LifecycleStateEnum.CERTIFIED)){ + 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()); + 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.getUserId().equals(owner.getUserId()) && !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()); + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.getUserId().equals(owner.getUserId()) && !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); } private void updateCalculatedCapabilitiesRequirements(ToscaElement toscaElement) { - if(toscaElement.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE && toscaElement.getResourceType() != ResourceTypeEnum.CVFC){ + if (toscaElement.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE && toscaElement.getResourceType() != ResourceTypeEnum.CVFC) { toscaOperationFacade.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement.getUniqueId()); } } 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 352371c3d9..44505ec10c 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 @@ -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. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.lifecycle; import fj.data.Either; +import java.util.Arrays; +import java.util.List; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -48,23 +49,19 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.Arrays; -import java.util.List; - public class CheckoutTransition extends LifeCycleTransition { private static final Logger log = Logger.getLogger(CheckoutTransition.class); - CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, + JanusGraphDao janusGraphDao) { super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + 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 @@ -78,39 +75,36 @@ public class CheckoutTransition extends LifeCycleTransition { } @Override - public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - + 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()); - + 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(componentType == ComponentTypeEnum.SERVICE) { - Service service = (Service)clonedComponent; + if (componentType == ComponentTypeEnum.SERVICE) { + Service service = (Service) clonedComponent; service.validateAndSetInstantiationType(); } - if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NODE_TYPE ){ + if (checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NODE_TYPE) { Either upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent); - if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){ + if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()) { result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value())); return result; } - if ( upgradeToLatestDerived.isLeft() ){ + if (upgradeToLatestDerived.isLeft()) { //get resource after update derived clonedComponent = upgradeToLatestDerived.left().value(); } @@ -119,7 +113,7 @@ public class CheckoutTransition extends LifeCycleTransition { Either upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent); if (upgradeToLatestGeneric.isRight()) { result = Either.right(upgradeToLatestGeneric.right().value()); - } else if (upgradeToLatestGeneric.left().value() ) { + } else if (upgradeToLatestGeneric.left().value()) { StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent); if (StorageOperationStatus.OK != response) { ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); @@ -128,9 +122,8 @@ public class CheckoutTransition extends LifeCycleTransition { } } handleCalculatedCapabilitiesRequirements(clonedComponent); - updateCapReqPropertiesOwnerId(clonedComponent); + updateCapReqPropertiesOwnerId(clonedComponent); } - } finally { if (result == null || result.isRight()) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); @@ -149,34 +142,36 @@ public class CheckoutTransition extends LifeCycleTransition { } private void handleCalculatedCapabilitiesRequirements(Component clonedComponent) { - if(clonedComponent.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(clonedComponent)){ + if (clonedComponent.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(clonedComponent)) { toscaOperationFacade.revertNamesOfCalculatedCapabilitiesRequirements(clonedComponent.getUniqueId()); } } private void updateCapReqPropertiesOwnerId(Component component) { - if(component.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(component)) { + if (component.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(component)) { toscaOperationFacade.updateCapReqPropertiesOwnerId(component.getUniqueId()); } } - private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) { + 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); + 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) { + 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()) { @@ -184,10 +179,11 @@ public class CheckoutTransition extends LifeCycleTransition { } // 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()); + ResponseFormat error = componentUtils + .getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_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/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java index 65fd1b8d42..bd3923e9ac 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 @@ -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. @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.lifecycle; import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -42,10 +44,6 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public abstract class LifeCycleTransition { protected ConfigurationManager configurationManager; @@ -54,14 +52,12 @@ public abstract class LifeCycleTransition { @Autowired protected JanusGraphDao janusGraphDao; protected ComponentsUtils componentUtils; - protected Map> authorizedRoles; protected Map> resourceAuthorizedRoles; - ToscaOperationFacade toscaOperationFacade; - protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { - + protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, + ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { this.configurationManager = ConfigurationManager.getConfigurationManager(); this.lifeCycleOperation = lifecycleOperation2; this.componentUtils = componentUtils; @@ -107,58 +103,66 @@ public abstract class LifeCycleTransition { 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 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) { + 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); } protected Either getComponentOwner(Component component, ComponentTypeEnum componentType) { - Either resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId()); if (resourceOwnerResult.isRight()) { - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType); + 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) { - + 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)) { + 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)) { + 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()))) { + 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 43714f2756..6f4c6416f0 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 @@ -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. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.lifecycle; import com.google.common.annotations.VisibleForTesting; @@ -69,67 +68,51 @@ import org.springframework.context.annotation.Lazy; public class LifecycleBusinessLogic { private static final String COMMENT = "comment"; - + private static final Logger log = Logger.getLogger(LifecycleBusinessLogic.class); + @Autowired + ToscaOperationFacade toscaOperationFacade; + @Autowired + NodeTemplateOperation nodeTemplateOperation; + @Autowired + CatalogOperation catalogOperations; + @Autowired + VesionUpdateHandler groupUpdateHandler; @Autowired private IGraphLockOperation graphLockOperation = null; - @Autowired private JanusGraphDao janusGraphDao; - - private static final Logger log = Logger.getLogger(LifecycleBusinessLogic.class); - @javax.annotation.Resource private ComponentsUtils componentUtils; - @javax.annotation.Resource private ToscaElementLifecycleOperation lifecycleOperation; - @Autowired @Lazy private ServiceBusinessLogic serviceBusinessLogic; - @Autowired @Lazy private ResourceBusinessLogic resourceBusinessLogic; - @Autowired @Lazy private ProductBusinessLogic productBusinessLogic; - - @Autowired - ToscaOperationFacade toscaOperationFacade; - - @Autowired - NodeTemplateOperation nodeTemplateOperation; - - @Autowired - CatalogOperation catalogOperations; - - @Autowired - VesionUpdateHandler groupUpdateHandler; - private Map stateTransitions; @PostConstruct public void init() { - initStateOperations(); + initStateOperations(); } private void initStateOperations() { stateTransitions = new HashMap<>(); - - LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, - janusGraphDao); + LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); stateTransitions.put(checkoutOp.getName().name(), checkoutOp); - UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); undoCheckoutOp.setCatalogOperations(catalogOperations); stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp); - - LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao, groupUpdateHandler); + LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao, + groupUpdateHandler); stateTransitions.put(checkinOp.getName().name(), checkinOp); - - CertificationChangeTransition successCertification = new CertificationChangeTransition(serviceBusinessLogic, LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); + CertificationChangeTransition successCertification = new CertificationChangeTransition(serviceBusinessLogic, LifeCycleTransitionEnum.CERTIFY, + componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); successCertification.setNodeTemplateOperation(nodeTemplateOperation); stateTransitions.put(successCertification.getName().name(), successCertification); } @@ -140,19 +123,15 @@ public class LifecycleBusinessLogic { } // TODO: rhalili - should use changeComponentState when possible - public Either changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { + public Either changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, + LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { return changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); } - public Either changeComponentState( - ComponentTypeEnum componentType, - String componentId, - User modifier, - LifeCycleTransitionEnum transitionEnum, - LifecycleChangeInfoWithAction changeInfo, - boolean inTransaction, - boolean needLock) { - + 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()); @@ -161,32 +140,24 @@ public class LifecycleBusinessLogic { } log.debug("get resource from graph"); ResponseFormat errorResponse; - - Either eitherResourceResponse = getComponentForChange( - componentType, componentId, modifier, lifeCycleTransition, changeInfo - ); + Either eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, + changeInfo); if (eitherResourceResponse.isRight()) { return eitherResourceResponse; } T component = eitherResourceResponse.left().value(); String resourceCurrVersion = component.getVersion(); LifecycleStateEnum resourceCurrState = component.getLifecycleState(); - // lock resource if (!inTransaction && needLock) { log.debug("lock component {}", componentId); try { lockComponent(componentType, component); - }catch (ComponentException e){ + } catch (ComponentException e) { errorResponse = e.getResponseFormat(); componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), - new ResourceCommonInfo(componentType.getValue()), - ResourceVersionInfo.newBuilder() - .state(resourceCurrState.name()) - .version(resourceCurrVersion) - .build()); - - + new ResourceCommonInfo(componentType.getValue()), + ResourceVersionInfo.newBuilder().state(resourceCurrState.name()).version(resourceCurrVersion).build()); log.error("lock component {} failed", componentId); return Either.right(errorResponse); } @@ -197,34 +168,28 @@ public class LifecycleBusinessLogic { if (commentValidationResult.isRight()) { errorResponse = commentValidationResult.right().value(); componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), - new ResourceCommonInfo(componentType.getValue()), - ResourceVersionInfo.newBuilder() - .state(resourceCurrState.name()) - .version(resourceCurrVersion) - .build(), - changeInfo.getUserRemarks()); + new ResourceCommonInfo(componentType.getValue()), + ResourceVersionInfo.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); + Either validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, + resourceCurrVersion, componentType); if (validateHighestVersion.isRight()) { return Either.right(validateHighestVersion.right().value()); } log.debug("after validate Highest Version"); final T oldComponent = component; - Either checkedInComponentEither = - checkInBeforeCertifyIfNeeded(componentType, modifier, transitionEnum, changeInfo, inTransaction, - component); - if(checkedInComponentEither.isRight()) { + Either checkedInComponentEither = checkInBeforeCertifyIfNeeded(componentType, modifier, transitionEnum, changeInfo, + inTransaction, component); + if (checkedInComponentEither.isRight()) { return Either.right(checkedInComponentEither.right().value()); } component = checkedInComponentEither.left().value(); - return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction) - .left() - .bind(c -> updateCatalog(c, oldComponent, ChangeTypeEnum.LIFECYCLE)); - - + return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction).left() + .bind(c -> updateCatalog(c, oldComponent, ChangeTypeEnum.LIFECYCLE)); } finally { component.setUniqueId(componentId); if (!inTransaction && needLock) { @@ -232,152 +197,106 @@ public class LifecycleBusinessLogic { NodeTypeEnum nodeType = componentType.getNodeType(); log.info("During change state, another component {} has been created/updated", componentId); graphLockOperation.unlockComponent(componentId, nodeType); - } } - } - private Either updateCatalog( - T component, - T oldComponent, - ChangeTypeEnum changeStatus - ){ - + private Either updateCatalog(T component, T oldComponent, ChangeTypeEnum changeStatus) { log.debug("updateCatalog start"); - T result = component == null? oldComponent : component; - if(component != null){ - ActionStatus status = catalogOperations.updateCatalog(changeStatus,component); - if(status != ActionStatus.OK){ - return Either.right(componentUtils.getResponseFormat(status)); - } + T result = component == null ? oldComponent : component; + if (component != null) { + ActionStatus status = catalogOperations.updateCatalog(changeStatus, component); + if (status != ActionStatus.OK) { + return Either.right(componentUtils.getResponseFormat(status)); + } } - - return Either.left(result); + return Either.left(result); } - private Either checkInBeforeCertifyIfNeeded( - ComponentTypeEnum componentType, - User modifier, - LifeCycleTransitionEnum transitionEnum, - LifecycleChangeInfoWithAction changeInfo, - boolean inTransaction, - T component - ) { - + private Either checkInBeforeCertifyIfNeeded(ComponentTypeEnum componentType, User modifier, + LifeCycleTransitionEnum transitionEnum, + LifecycleChangeInfoWithAction changeInfo, + boolean inTransaction, T component) { LifecycleStateEnum oldState = component.getLifecycleState(); log.debug("Certification request for resource {} ", component.getUniqueId()); if (oldState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT && transitionEnum == LifeCycleTransitionEnum.CERTIFY) { log.debug("Resource {} is in Checkout state perform checkin", component.getUniqueId()); - Either actionResponse = changeState( - component, - stateTransitions.get(LifeCycleTransitionEnum.CHECKIN.name()), + Either actionResponse = changeState(component, stateTransitions.get(LifeCycleTransitionEnum.CHECKIN.name()), componentType, modifier, changeInfo, inTransaction); if (actionResponse.isRight()) { log.debug("Failed to check in Resource {} error {}", component.getUniqueId(), actionResponse.right().value()); } return actionResponse; } - return Either.left(component); } - private Either changeState( - T component, - LifeCycleTransition lifeCycleTransition, - ComponentTypeEnum componentType, - User modifier, - LifecycleChangeInfoWithAction changeInfo, - boolean inTransaction - ) { + private Either changeState(T 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); 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); + 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(), - new ResourceCommonInfo(componentType.getValue()), - ResourceVersionInfo.newBuilder() - .version(resourceCurrVersion) - .state(oldState.name()) - .build(), - changeInfo.getUserRemarks()); + new ResourceCommonInfo(componentType.getValue()), + ResourceVersionInfo.newBuilder().version(resourceCurrVersion).state(oldState.name()).build(), changeInfo.getUserRemarks()); return Either.right(errorResponse); } - - Either operationResult = lifeCycleTransition.changeState( - componentType, component, bl, modifier, owner, false, inTransaction); - + 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, - ResourceVersionInfo.newBuilder() - .state(oldState.name()) - .version(resourceCurrVersion) - .build()); - + ResourceVersionInfo.newBuilder().state(oldState.name()).version(resourceCurrVersion).build()); return Either.right(errorResponse); } - Component resourceAfterOperation = operationResult.left().value() == null? component: operationResult.left().value() ; + Component resourceAfterOperation = operationResult.left().value() == null ? component : operationResult.left().value(); componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, - lifeCycleTransition.getAuditingAction(), new ResourceCommonInfo(componentType.getValue()), - ResourceVersionInfo.newBuilder() - .state(oldState.name()) - .version(resourceCurrVersion) - .build(), - changeInfo.getUserRemarks()); + lifeCycleTransition.getAuditingAction(), new ResourceCommonInfo(componentType.getValue()), + ResourceVersionInfo.newBuilder().state(oldState.name()).version(resourceCurrVersion).build(), changeInfo.getUserRemarks()); return operationResult; - } - - private Either getComponentForChange( - ComponentTypeEnum componentType, - String componentId, - User modifier, - LifeCycleTransition lifeCycleTransition, - LifecycleChangeInfoWithAction changeInfo - ) { - + 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(), - new ResourceCommonInfo(componentId, componentType.getValue()), changeInfo.getUserRemarks()); - + new ResourceCommonInfo(componentId, componentType.getValue()), changeInfo.getUserRemarks()); return Either.right(errorResponse); } return Either.left(eitherResourceResponse.left().value()); } - private Either validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component, String resourceCurrVersion, ComponentTypeEnum componentType) { + 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()); + 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, - ResourceVersionInfo.newBuilder() - .state(component.getLifecycleState().name()) - .version(resourceCurrVersion) - .build()); + ResourceVersionInfo.newBuilder().state(component.getLifecycleState().name()).version(resourceCurrVersion).build()); return Either.right(errorResponse); } return Either.left(true); @@ -386,35 +305,33 @@ public class LifecycleBusinessLogic { private Boolean lockComponent(ComponentTypeEnum componentType, Component component) { NodeTypeEnum nodeType = componentType.getNodeType(); StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(component.getUniqueId(), nodeType); - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { return true; } else { ActionStatus actionStatus = componentUtils.convertFromStorageResponse(lockResourceStatus); - throw new ByActionStatusComponentException(actionStatus, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + throw new ByActionStatusComponentException(actionStatus, + component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); } } private Either validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) { String comment = changeInfo.getUserRemarks(); if (LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum - // import? + // 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))); + 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)); @@ -426,39 +343,35 @@ public class LifecycleBusinessLogic { 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()); + 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)); + 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, as only a state and a version is promoted due a Force certification, skipping other actions required if a previous certified version - * exists. - * + * Performs Force certification. Note that a Force certification is allowed for the first certification only, as only a state and a version is + * promoted due a Force certification, skipping other actions required if a previous certified version exists. + * * @param resource * @param user * @param lifecycleChangeInfo @@ -466,7 +379,8 @@ public class LifecycleBusinessLogic { * @param needLock * @return */ - public Resource forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + public Resource forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, + boolean needLock) { Resource result = null; Either certifyResourceRes = null; if (lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR) { @@ -474,7 +388,8 @@ public class LifecycleBusinessLogic { throw new ByActionStatusComponentException(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()); + log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ", + resource.getName()); throw new ByActionStatusComponentException(ActionStatus.NOT_ALLOWED); } // lock resource @@ -484,11 +399,13 @@ public class LifecycleBusinessLogic { log.info("after lock component {}", resource.getUniqueId()); } try { - certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion()); + 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); - throw new ByResponseFormatComponentException(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource)); + throw new ByResponseFormatComponentException( + componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource)); } result = ModelConverter.convertFromToscaElement(certifyResourceRes.left().value()); resource.setComponentMetadataDefinition(result.getComponentMetadataDefinition()); @@ -513,5 +430,4 @@ public class LifecycleBusinessLogic { 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 239f15ad5f..bde13f6fa0 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 @@ -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. @@ -17,13 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.lifecycle; import com.fasterxml.jackson.annotation.JsonInclude; public class LifecycleChangeInfoBase { + @JsonInclude + private String userRemarks; + public LifecycleChangeInfoBase() { } @@ -32,9 +34,6 @@ public class LifecycleChangeInfoBase { this.userRemarks = userRemarks; } - @JsonInclude - private String userRemarks; - public String getUserRemarks() { return 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 3df42e4857..cdec76468d 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 @@ -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. @@ -17,17 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.lifecycle; import com.fasterxml.jackson.annotation.JsonInclude; public class LifecycleChangeInfoWithAction extends LifecycleChangeInfoBase { - public enum LifecycleChanceActionEnum { - CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION - }; - @JsonInclude private LifecycleChanceActionEnum action; @@ -50,4 +45,6 @@ public class LifecycleChangeInfoWithAction extends LifecycleChangeInfoBase { public void setAction(LifecycleChanceActionEnum action) { this.action = action; } + + public enum LifecycleChanceActionEnum {CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION} } 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 c66f7ea5dd..0502741e7e 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 @@ -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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.lifecycle; import fj.data.Either; +import java.util.Arrays; import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -43,23 +43,20 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.Arrays; - public class UndoCheckoutTransition extends LifeCycleTransition { - private static final Logger log = Logger.getLogger(CheckoutTransition.class); + private static final Logger log = Logger.getLogger(CheckoutTransition.class); private CatalogOperation catalogOperations; - public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { + public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, + ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) { super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao); - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + 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 @@ -77,54 +74,52 @@ public class UndoCheckoutTransition extends LifeCycleTransition { } @Override - public 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, 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); + 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()); + 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()); + 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) { - + 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.right(responseFormat); + } else { ToscaElement element = undoCheckoutResourceResult.left().value(); - if(element == null){ + if (element == null) { catalogOperations.updateCatalog(ChangeTypeEnum.DELETE, component); result = Either.left(null); - } - else{ - result = Either.left(ModelConverter.convertFromToscaElement(element)); + } else { + result = Either.left(ModelConverter.convertFromToscaElement(element)); } } } finally { @@ -139,6 +134,4 @@ public class UndoCheckoutTransition extends LifeCycleTransition { } return result; } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsGlobalMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsGlobalMergeCommand.java index df5c0c6a51..e361f581f6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsGlobalMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsGlobalMergeCommand.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. @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge; /** * A command to be executed upon csar update in case new csar topology was changed with respect to previous csar */ public interface ComponentsGlobalMergeCommand extends ComponentsMergeCommand { + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsMergeCommand.java index 16b75ffc5f..ad2d3a235d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsMergeCommand.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -27,16 +26,15 @@ 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 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/GlobalInputsFilteringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java index c4f128f7c7..66f237b9f5 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 @@ -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. @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge; import fj.data.Either; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -30,10 +32,6 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - @org.springframework.stereotype.Component public class GlobalInputsFilteringBusinessLogic { @@ -41,16 +39,18 @@ public class GlobalInputsFilteringBusinessLogic { private ToscaOperationFacade toscaOperationFacade; private ComponentsUtils componentsUtils; - public GlobalInputsFilteringBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { + public GlobalInputsFilteringBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic, ToscaOperationFacade toscaOperationFacade, + ComponentsUtils componentsUtils) { this.genericTypeBusinessLogic = genericTypeBusinessLogic; this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; } public Either, ActionStatus> filterGlobalInputs(Component newResource) { - Either genericComp = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(newResource.fetchGenericTypeToscaNameFromConfig()); - return genericComp.bimap(genericResource -> findCommonInputs(genericResource, newResource), - storageOperationStatus -> componentsUtils.convertFromStorageResponse(storageOperationStatus)); + Either genericComp = toscaOperationFacade + .getLatestCertifiedNodeTypeByToscaResourceName(newResource.fetchGenericTypeToscaNameFromConfig()); + return genericComp.bimap(genericResource -> findCommonInputs(genericResource, newResource), + storageOperationStatus -> componentsUtils.convertFromStorageResponse(storageOperationStatus)); } private List findCommonInputs(Resource genericResource, Component resource) { @@ -59,5 +59,4 @@ public class GlobalInputsFilteringBusinessLogic { Set genericInputsNames = genericInputs.stream().map(InputDefinition::getName).collect(Collectors.toSet()); return resourceInputs.stream().filter(input -> genericInputsNames.contains(input.getName())).collect(Collectors.toList()); } - } 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 47f71cb05d..0c64538484 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 @@ -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. @@ -17,30 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 { /** - * * @param oldResource the old resource * @param newResource the new resource - * @return true if there was a change in one of the relations between the old and new resource - * a change in relation is determine by comparing the relations type, node, capability and requirement name + * @return true if there was a change in one of the relations between the old and new resource a change in relation is determine by comparing the + * relations type, node, capability and requirement name */ - public boolean isRelationsChanged(Resource oldResource, Resource newResource) { + public boolean isRelationsChanged(Resource oldResource, Resource newResource) { Map> oldRelationsByInstance = oldResource.groupRelationsFromCsarByInstanceName(oldResource); Map> newRelationsByInstance = newResource.groupRelationsFromCsarByInstanceName(newResource); for (Map.Entry> relationByInst : newRelationsByInstance.entrySet()) { @@ -51,48 +48,48 @@ public class RelationsComparator { } } return false; - } - private boolean isInstanceRelationsChanged(Resource oldResource, List oldRelations, Resource newResource, List newRelations) { - if (oldRelations == null || oldRelations.size() != newRelations.size()){ + private boolean isInstanceRelationsChanged(Resource oldResource, List oldRelations, Resource newResource, + List newRelations) { + if (oldRelations == null || oldRelations.size() != newRelations.size()) { return true; } return newRelations.stream().anyMatch(newRelation -> !findRelation(oldResource, oldRelations, newResource, newRelation)); } - - - private boolean findRelation(Resource oldResource, List oldRelations, Resource newResource, RequirementCapabilityRelDef newRelation) { + private boolean findRelation(Resource oldResource, List oldRelations, Resource newResource, + RequirementCapabilityRelDef newRelation) { for (RequirementCapabilityRelDef oldRelation : oldRelations) { RelationshipInfo oldRelationship = oldRelation.resolveSingleRelationship().getRelation(); RelationshipInfo newRelationship = newRelation.resolveSingleRelationship().getRelation(); - if (oldRelationship != null && newRelationship != null && isRelationEqual(oldRelationship, newRelationship) && isRelationToNodeEquals(oldResource, oldRelation, newResource, newRelation)) { + if (oldRelationship != null && newRelationship != null && isRelationEqual(oldRelationship, newRelationship) && isRelationToNodeEquals( + oldResource, oldRelation, newResource, newRelation)) { return true; } } return false; } - private boolean isRelationToNodeEquals(Resource oldResource, RequirementCapabilityRelDef oldRelation, Resource newResource, RequirementCapabilityRelDef newRelation) { + private boolean isRelationToNodeEquals(Resource oldResource, RequirementCapabilityRelDef oldRelation, Resource newResource, + RequirementCapabilityRelDef newRelation) { String oldToNodeId = oldRelation.getToNode(); String newToNodeId = newRelation.getToNode(); Optional oldRelationToNode = oldResource.getComponentInstanceById(oldToNodeId); Optional newRelationToNode = newResource.getComponentInstanceById(newToNodeId); - return oldRelationToNode.isPresent() && newRelationToNode.isPresent() && oldRelationToNode.get().getInvariantName().equals(newRelationToNode.get().getInvariantName()); + return oldRelationToNode.isPresent() && newRelationToNode.isPresent() && oldRelationToNode.get().getInvariantName() + .equals(newRelationToNode.get().getInvariantName()); } private boolean isRelationEqual(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { - return isRelationshipTypeEquals(oldRelationship, newRelationship) && - isRelationshipCapabilityEquals(oldRelationship, newRelationship) && - isRelationshipReqNameEquals(oldRelationship, newRelationship); + return isRelationshipTypeEquals(oldRelationship, newRelationship) && isRelationshipCapabilityEquals(oldRelationship, newRelationship) + && isRelationshipReqNameEquals(oldRelationship, newRelationship); } private boolean isRelationshipCapabilityEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { - if(oldRelationship.getCapabilityUid() !=null && newRelationship.getCapabilityUid() != null){ + if (oldRelationship.getCapabilityUid() != null && newRelationship.getCapabilityUid() != null) { return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid()); - } - else if(oldRelationship.getCapabilityUid() == null && newRelationship.getCapabilityUid() == null){ + } else if (oldRelationship.getCapabilityUid() == null && newRelationship.getCapabilityUid() == null) { return true; } return false; @@ -103,13 +100,11 @@ public class RelationsComparator { } private boolean isRelationshipReqNameEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { - if(oldRelationship.getRequirement() != null && newRelationship.getRequirement() != null){ + if (oldRelationship.getRequirement() != null && newRelationship.getRequirement() != null) { return oldRelationship.getRequirement().equals(newRelationship.getRequirement()); - } - else if(oldRelationship.getRequirement() == null && newRelationship.getRequirement() == null){ + } else if (oldRelationship.getRequirement() == null && newRelationship.getRequirement() == null) { return true; } 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 24e669a92d..bb84a57d5d 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 @@ -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. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge; import fj.data.Either; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.exception.SdcActionException; @@ -32,29 +33,22 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.List; -import java.util.Map; - @org.springframework.stereotype.Component public class TopologyComparator { public static final Logger log = Logger.getLogger(TopologyComparator.class); - @javax.annotation.Resource private RelationsComparator relationsComparator; - @javax.annotation.Resource private ToscaOperationFacade toscaOperationFacade; - @javax.annotation.Resource private ComponentsUtils componentsUtils; /** - * * @param oldResource the old version of the resource of which to check for topology change * @param newResource the new version of the resource of which to check for topology change - * @return true if there was a topology change between the old resource and new resource or false otherwise - * in case the action to find topology change failed, an appropriate {@link ActionStatus} will be returned + * @return true if there was a topology change between the old resource and new resource or false otherwise in case the action to find topology + * change failed, an appropriate {@link ActionStatus} will be returned */ public Either isTopologyChanged(Resource oldResource, Resource newResource) { List oldInstances = oldResource.getComponentInstances(); @@ -70,14 +64,17 @@ public class TopologyComparator { return isTopologyInstancesChanged(oldResource, newResource, oldInstancesByName, newInstancesByName); } - private Either isTopologyInstancesChanged(Resource oldResource, Resource newResource, Map oldInstancesByName, Map newInstancesByName) { + private Either isTopologyInstancesChanged(Resource oldResource, Resource newResource, + Map oldInstancesByName, + Map newInstancesByName) { try { - boolean isTopologyChanged = isInstanceNamesChanged(oldInstancesByName, newInstancesByName) || - isInstanceTypesChanged(oldInstancesByName, newInstancesByName) || - relationsComparator.isRelationsChanged(oldResource, newResource); + boolean isTopologyChanged = + isInstanceNamesChanged(oldInstancesByName, newInstancesByName) || isInstanceTypesChanged(oldInstancesByName, newInstancesByName) + || relationsComparator.isRelationsChanged(oldResource, newResource); return Either.left(isTopologyChanged); } catch (SdcActionException e) { - log.error("failed to merge entities of previous resource %s to current resource %s. reason: %s", oldResource.getUniqueId(), newResource.getUniqueId(), e.getActionStatus(), e); + log.error("failed to merge entities of previous resource %s to current resource %s. reason: %s", oldResource.getUniqueId(), + newResource.getUniqueId(), e.getActionStatus(), e); return Either.right(e.getActionStatus()); } } @@ -97,8 +94,7 @@ public class TopologyComparator { } private boolean isSameToscaTypeOrOriginComponent(ComponentInstance oldInstance, ComponentInstance newInstance) { - return isSameToscaType(oldInstance, newInstance) || - isSameOriginComponent(oldInstance, newInstance); + return isSameToscaType(oldInstance, newInstance) || isSameOriginComponent(oldInstance, newInstance); } private boolean isSameToscaType(ComponentInstance oldInstance, ComponentInstance newInstance) { @@ -109,8 +105,10 @@ public class TopologyComparator { if (oldInstance.getComponentUid().equals(newInstance.getComponentUid())) { return true; } - Component oldOriginCmpt = toscaOperationFacade.getToscaElement(oldInstance.getComponentUid()).left().on(storageStatus -> throwSdcActionException(storageStatus, oldInstance)); - Component newOriginCmpt = toscaOperationFacade.getToscaElement(newInstance.getComponentUid()).left().on(storageStatus -> throwSdcActionException(storageStatus, newInstance)); + Component oldOriginCmpt = toscaOperationFacade.getToscaElement(oldInstance.getComponentUid()).left() + .on(storageStatus -> throwSdcActionException(storageStatus, oldInstance)); + Component newOriginCmpt = toscaOperationFacade.getToscaElement(newInstance.getComponentUid()).left() + .on(storageStatus -> throwSdcActionException(storageStatus, newInstance)); return oldOriginCmpt.getInvariantUUID().equals(newOriginCmpt.getInvariantUUID()); } @@ -118,6 +116,4 @@ public class TopologyComparator { log.error("failed to fetch origin node type %s for instance %s", cmptInstance.getUniqueId(), cmptInstance.getComponentUid()); throw new SdcActionException(componentsUtils.convertFromStorageResponse(storageOperationStatus)); } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/VspComponentsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/VspComponentsMergeCommand.java index 44fbc9ab88..1cfc53e9c5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/VspComponentsMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/VspComponentsMergeCommand.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge; /** @@ -25,5 +24,4 @@ package org.openecomp.sdc.be.components.merge; */ public interface VspComponentsMergeCommand extends ComponentsMergeCommand { - } 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 index 9ec7104773..4b5efbef1d 100644 --- 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 @@ -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. @@ -17,31 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.capability; +import java.util.List; +import java.util.Map; 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 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 + * @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); + 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 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) */ 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 index 3f6ed7d7b2..85fe6926ce 100644 --- 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 @@ -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. @@ -17,23 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.capability; -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 static java.util.stream.Collectors.toList; +import static org.openecomp.sdc.be.dao.utils.MapUtil.flattenMapValues; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; +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 static java.util.stream.Collectors.toList; -import static org.openecomp.sdc.be.dao.utils.MapUtil.flattenMapValues; @org.springframework.stereotype.Component public class SimpleCapabilityResolver implements CapabilityResolver { @@ -44,27 +43,36 @@ public class SimpleCapabilityResolver implements CapabilityResolver { } @Override - public Map resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List prevCapabilities) { + public Map resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, + String cmptInstanceId, + List prevCapabilities) { List newCapabilities = resolveInstanceCapabilities(container, cmptInstanceId); - Map oldCapOwnerToNewOwner = mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, cmptInstanceId, prevCapabilities); + Map oldCapOwnerToNewOwner = mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, cmptInstanceId, + prevCapabilities); return mapOldToNewCapabilities(prevCapabilities, newCapabilities, oldCapOwnerToNewOwner); } @Override - public Map resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, ComponentInstance currInstance) { + public Map resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, + ComponentInstance currInstance) { List newCapabilities = flattenMapValues(currInstance.getCapabilities()); List prevCapabilities = flattenMapValues(oldInstance.getCapabilities()); Map oldCapOwnerToNewOwner = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance); return mapOldToNewCapabilities(prevCapabilities, newCapabilities, oldCapOwnerToNewOwner); } - private Map mapOldToNewCapabilities(List prevCapabilities, List newCapabilities, Map oldCapOwnerToNewOwner) { - Map oldToNewCapability = findNewCapByPrevCapabilityNameTypeAndOwner(prevCapabilities, newCapabilities, oldCapOwnerToNewOwner); + private Map mapOldToNewCapabilities(List prevCapabilities, + List newCapabilities, + Map oldCapOwnerToNewOwner) { + Map oldToNewCapability = findNewCapByPrevCapabilityNameTypeAndOwner(prevCapabilities, + newCapabilities, oldCapOwnerToNewOwner); removeNotFoundNewCapabilities(oldToNewCapability); return oldToNewCapability; } - private Map findNewCapByPrevCapabilityNameTypeAndOwner(List prevCapabilities, List newCapabilities, Map oldCapOwnerToNewOwner) { + private Map findNewCapByPrevCapabilityNameTypeAndOwner(List prevCapabilities, + List newCapabilities, + Map oldCapOwnerToNewOwner) { Map prevToNewCapabilityMapping = new HashMap<>(); prevCapabilities.forEach(prevCap -> { CapabilityDefinition newCapability = mapOldToNewCapability(prevCap, newCapabilities, oldCapOwnerToNewOwner); @@ -73,18 +81,16 @@ public class SimpleCapabilityResolver implements CapabilityResolver { return prevToNewCapabilityMapping; } - private CapabilityDefinition mapOldToNewCapability(CapabilityDefinition prevCap, List newCapabilities, Map oldCapOwnerToNewOwner) { + private CapabilityDefinition mapOldToNewCapability(CapabilityDefinition prevCap, List newCapabilities, + Map oldCapOwnerToNewOwner) { String newOwnerId = oldCapOwnerToNewOwner.get(prevCap.getOwnerId()); - return newCapabilities.stream() - .filter(newCap -> newCap.getName().equals(prevCap.getName())) - .filter(newCap -> newCap.getType().equals(prevCap.getType())) - .filter(newCap -> newCap.getOwnerId().equals(newOwnerId)) - .findFirst() - .orElse(null); + return newCapabilities.stream().filter(newCap -> newCap.getName().equals(prevCap.getName())) + .filter(newCap -> newCap.getType().equals(prevCap.getType())).filter(newCap -> newCap.getOwnerId().equals(newOwnerId)).findFirst() + .orElse(null); } - - private Map mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String cmptInstanceId, List prevCapabilities) { + private Map mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String cmptInstanceId, + List prevCapabilities) { List prevCapOwnerIds = prevCapabilities.stream().map(CapabilityDefinition::getOwnerId).distinct().collect(toList()); return mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, origInstanceNode, cmptInstanceId, prevCapOwnerIds); } @@ -94,14 +100,7 @@ public class SimpleCapabilityResolver implements CapabilityResolver { } private List resolveInstanceCapabilities(Component capabilityOwnerContainer, String cmptInstanceId) { - return capabilityOwnerContainer.getComponentInstanceById(cmptInstanceId) - .map(ComponentInstance::getCapabilities) - .map(MapUtil::flattenMapValues) - .orElse(new ArrayList<>()); + return capabilityOwnerContainer.getComponentInstanceById(cmptInstanceId).map(ComponentInstance::getCapabilities) + .map(MapUtil::flattenMapValues).orElse(new ArrayList<>()); } - - - - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.java index dc3f2059a2..560d17dc50 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.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. @@ -17,9 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.group; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.apache.commons.collections.MapUtils.isEmpty; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.FIRST_COMMAND; + +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand; import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -31,16 +39,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.core.annotation.Order; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toMap; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.apache.commons.collections.MapUtils.isEmpty; -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.FIRST_COMMAND; - @org.springframework.stereotype.Component @Order(FIRST_COMMAND)//must run before policies merge command public class ComponentGroupMergeCommand implements VspComponentsMergeCommand, ComponentsGlobalMergeCommand { @@ -71,15 +69,11 @@ public class ComponentGroupMergeCommand implements VspComponentsMergeCommand, Co } updateGroupsMembers(prevUserDefinedGroups, prevComponent, currentComponent); return associateGroupsToComponent(currentComponent, prevUserDefinedGroups); - } private List getAllPreviouslyUserDefinedGroups(Component prevComponent, Component currCmpt) { - return prevComponent.getGroups() - .stream() - .filter(GroupDefinition::isUserDefined) - .filter(group -> !currCmpt.containsGroupWithInvariantName(group.getInvariantName())) - .collect(toList()); + return prevComponent.getGroups().stream().filter(GroupDefinition::isUserDefined) + .filter(group -> !currCmpt.containsGroupWithInvariantName(group.getInvariantName())).collect(toList()); } private void updateGroupsMembers(List prevUserDefinedGroups, Component prevComponent, Component currentComponent) { @@ -96,26 +90,16 @@ public class ComponentGroupMergeCommand implements VspComponentsMergeCommand, Co return findNewInstancesByPrevInstancesNames(prevComponent, currentComponent, prevGroupMembers); } - private Map findNewInstancesByPrevInstancesNames(Component prevComponent, Component currentComponent, Map prevGroupMembers) { - return prevGroupMembers.values() - .stream() - .map(prevComponent::getComponentInstanceById) - .filter(Optional::isPresent) - .map(Optional::get) - .map(prevInstance -> currentComponent.getComponentInstanceByName(prevInstance.getName())) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + private Map findNewInstancesByPrevInstancesNames(Component prevComponent, Component currentComponent, + Map prevGroupMembers) { + return prevGroupMembers.values().stream().map(prevComponent::getComponentInstanceById).filter(Optional::isPresent).map(Optional::get) + .map(prevInstance -> currentComponent.getComponentInstanceByName(prevInstance.getName())).filter(Optional::isPresent).map(Optional::get) + .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); } private ActionStatus associateGroupsToComponent(Component currentComponent, List prevUserDefinedGroups) { currentComponent.addGroups(prevUserDefinedGroups); return groupsOperation.addGroups(currentComponent, prevUserDefinedGroups) - .either(addedGroups -> ActionStatus.OK, - componentsUtils::convertFromStorageResponse); + .either(addedGroups -> ActionStatus.OK, componentsUtils::convertFromStorageResponse); } - - - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.java index 00276a9363..c9621c369b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.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. @@ -17,9 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.group; +import static java.util.Collections.emptyList; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; + +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand; import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand; import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; @@ -33,16 +41,6 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation; import org.springframework.core.annotation.Order; -import java.util.List; -import java.util.Map; - -import static java.util.Collections.emptyList; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toMap; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; - @org.springframework.stereotype.Component @Order(ANY_ORDER_COMMAND) public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, ComponentsGlobalMergeCommand { @@ -51,7 +49,8 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C private final ComponentsUtils componentsUtils; private final DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; - public GroupPropertiesMergeCommand(GroupsOperation groupsOperation, ComponentsUtils componentsUtils, DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) { + public GroupPropertiesMergeCommand(GroupsOperation groupsOperation, ComponentsUtils componentsUtils, + DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) { this.groupsOperation = groupsOperation; this.componentsUtils = componentsUtils; this.propertyValuesMergingBusinessLogic = propertyValuesMergingBusinessLogic; @@ -64,9 +63,10 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C /** * merge user defined group properties values from previous version into vsp defined groups in new version - * @param prevComponent the old component, whose group properties need to be merged from - * @param currentComponent the new component, whose group properties need to be merged into - * old and new component inputs are needed in order to determine if a "get_input" property value should be merged + * + * @param prevComponent the old component, whose group properties need to be merged from + * @param currentComponent the new component, whose group properties need to be merged into old and new component inputs are needed in order to + * determine if a "get_input" property value should be merged * @return the status of the merge operation */ @Override @@ -84,7 +84,8 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C return mergeGroupPropertiesValues(prevComponent, currentComponent, prevGroups, newGroups); } - private List mergeGroupPropertiesValues(Component prevComponent, Component currentComponent, List prevGroups, List newGroups) { + private List mergeGroupPropertiesValues(Component prevComponent, Component currentComponent, List prevGroups, + List newGroups) { Map prevGroupsByInvariantName = getVspGroupsMappedByInvariantName(prevGroups); List newGroupsExistInPrevVersion = getNewGroupsExistInPrevComponent(prevGroupsByInvariantName, newGroups); newGroupsExistInPrevVersion.forEach(newGroup -> { @@ -94,23 +95,20 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C return newGroupsExistInPrevVersion; } - private void mergeGroupProperties(GroupDefinition prevGroup, List prevInputs, GroupDefinition newGroup, List currInputs) { + private void mergeGroupProperties(GroupDefinition prevGroup, List prevInputs, GroupDefinition newGroup, + List currInputs) { propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(prevGroup.getProperties(), prevInputs, newGroup.getProperties(), currInputs); } - private List getNewGroupsExistInPrevComponent(Map prevGroupsByInvariantName, List newGroups) { - return newGroups.stream() - .filter(newGroup -> prevGroupsByInvariantName.containsKey(newGroup.getInvariantName())) - .filter(newGroup -> isNotEmpty(newGroup.getProperties())) - .collect(toList()); + private List getNewGroupsExistInPrevComponent(Map prevGroupsByInvariantName, + List newGroups) { + return newGroups.stream().filter(newGroup -> prevGroupsByInvariantName.containsKey(newGroup.getInvariantName())) + .filter(newGroup -> isNotEmpty(newGroup.getProperties())).collect(toList()); } private Map getVspGroupsMappedByInvariantName(List newGroups) { - return newGroups.stream() - .filter(GroupDataDefinition::isVspOriginated) - .filter(grp -> isNotEmpty(grp.getProperties())) - .collect(toMap(GroupDataDefinition::getInvariantName, - group -> group)); + return newGroups.stream().filter(GroupDataDefinition::isVspOriginated).filter(grp -> isNotEmpty(grp.getProperties())) + .collect(toMap(GroupDataDefinition::getInvariantName, group -> group)); } private ActionStatus updateGroups(Component currentComponent, List groupsToUpdate) { @@ -118,8 +116,6 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C return ActionStatus.OK; } return groupsOperation.updateGroups(currentComponent, groupsToUpdate, PromoteVersionEnum.MINOR) - .either(updatedGroups -> ActionStatus.OK, - err -> componentsUtils.convertFromStorageResponse(err, currentComponent.getComponentType())); + .either(updatedGroups -> ActionStatus.OK, err -> componentsUtils.convertFromStorageResponse(err, currentComponent.getComponentType())); } - } 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 20e3db0af2..2b1df01004 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 @@ -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. @@ -17,37 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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. */ @Component public class HeatEnvArtifactsMergeBusinessLogic { - public List mergeInstanceHeatEnvArtifacts(List origHeatEnvArtifacts, List newHeatEnvArtifacts) { + public List mergeInstanceHeatEnvArtifacts(List origHeatEnvArtifacts, + List newHeatEnvArtifacts) { Map origArtifactDefinitionByLabel = MapUtil.toMap(origHeatEnvArtifacts, ArtifactDefinition::getArtifactLabel); List artifactsToUpdate = new ArrayList<>(); - newHeatEnvArtifacts.stream() - .filter(heatEnvArtifact -> origArtifactDefinitionByLabel.containsKey(heatEnvArtifact.getArtifactLabel())) - .forEach(heatEnvArtifact -> { - ArtifactDefinition origHeatEnvArtifact = origArtifactDefinitionByLabel.get(heatEnvArtifact.getArtifactLabel()); - Boolean wasMergedHeatEnvArtifact = mergeHeatEnvArtifactsParameters(heatEnvArtifact, origHeatEnvArtifact); - if (wasMergedHeatEnvArtifact) { - artifactsToUpdate.add(heatEnvArtifact); - } - }); + newHeatEnvArtifacts.stream().filter(heatEnvArtifact -> origArtifactDefinitionByLabel.containsKey(heatEnvArtifact.getArtifactLabel())) + .forEach(heatEnvArtifact -> { + ArtifactDefinition origHeatEnvArtifact = origArtifactDefinitionByLabel.get(heatEnvArtifact.getArtifactLabel()); + Boolean wasMergedHeatEnvArtifact = mergeHeatEnvArtifactsParameters(heatEnvArtifact, origHeatEnvArtifact); + if (wasMergedHeatEnvArtifact) { + artifactsToUpdate.add(heatEnvArtifact); + } + }); return artifactsToUpdate; } @@ -55,13 +53,10 @@ public class HeatEnvArtifactsMergeBusinessLogic { List currentHeatEnvParams = currArtifact.getListHeatParameters(); List origHeatEnvParams = origArtifact.getListHeatParameters(); boolean wasChanged = false; - if (CollectionUtils.isEmpty(origHeatEnvParams) || CollectionUtils.isEmpty(currentHeatEnvParams)) { return false; } - Map origHeatParametersByName = MapUtil.toMap(origHeatEnvParams, HeatParameterDefinition::getName); - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { String paramName = currHeatParam.getName(); HeatParameterDefinition origHeatParam = origHeatParametersByName.get(paramName); @@ -75,10 +70,7 @@ public class HeatEnvArtifactsMergeBusinessLogic { } private boolean isSameHeatWithDiffValue(HeatParameterDefinition origHeatParam, HeatParameterDefinition newHeatParam) { - return origHeatParam != null && - origHeatParam.getCurrentValue() != null && - origHeatParam.getType().equals(newHeatParam.getType()) && - !origHeatParam.getCurrentValue().equals(newHeatParam.getCurrentValue()); + return origHeatParam != null && origHeatParam.getCurrentValue() != null && origHeatParam.getType().equals(newHeatParam.getType()) + && !origHeatParam.getCurrentValue().equals(newHeatParam.getCurrentValue()); } - } 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 0e88c8f710..6089bd292f 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 @@ -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. @@ -17,9 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.input; +import static java.util.stream.Collectors.toMap; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.PENULTIMATE_COMMAND; +import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.convertListOfProperties; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Stream; import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -29,20 +36,12 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.springframework.core.annotation.Order; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Stream; - -import static java.util.stream.Collectors.toMap; -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.PENULTIMATE_COMMAND; -import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.convertListOfProperties; - @org.springframework.stereotype.Component @Order(PENULTIMATE_COMMAND)//must run after all properties values were merged but before component instance relations merge public class ComponentInputsMergeBL extends InputsMergeCommand implements VspComponentsMergeCommand { - public ComponentInputsMergeBL(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { + public ComponentInputsMergeBL(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, + ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { super(inputsValuesMergingBusinessLogic, declaredInputsResolver, toscaOperationFacade, componentsUtils); } @@ -63,12 +62,9 @@ public class ComponentInputsMergeBL extends InputsMergeCommand implements VspCom @Override Map> getProperties(Component component) { - return Stream.of(component.safeGetComponentInstancesProperties(), - component.safeGetComponentInstancesInputs(), - component.safeGetGroupsProperties(), - component.safeGetPolicyProperties()) - .flatMap(map -> map.entrySet().stream()) - .collect(toMap(Entry::getKey, entry -> convertListOfProperties(entry.getValue()))); + return Stream + .of(component.safeGetComponentInstancesProperties(), component.safeGetComponentInstancesInputs(), component.safeGetGroupsProperties(), + component.safeGetPolicyProperties()).flatMap(map -> map.entrySet().stream()) + .collect(toMap(Entry::getKey, entry -> convertListOfProperties(entry.getValue()))); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/DeclaredInputsResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/DeclaredInputsResolver.java index 0d3d294844..2da3adec89 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/DeclaredInputsResolver.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/DeclaredInputsResolver.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. @@ -17,40 +17,40 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.input; +import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.resolveGetInputProperties; import com.google.common.base.Strings; -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.InputDefinition; - import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.resolveGetInputProperties; +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.InputDefinition; @org.springframework.stereotype.Component public class DeclaredInputsResolver { + /** * @param oldComponent the old state of {@link Component} that is being updated * @param newComponent the new state of {@link Component} that is being updated - * @param properties a list of properties - * @return a list of all inputs that were previously declared and need to be merged to the updating component - * An input needs to merged if a property was declared as an input (by the user) in previous component version and the declared input not exist in new version + * @param properties a list of properties + * @return a list of all inputs that were previously declared and need to be merged to the updating component An input needs to merged if a + * property was declared as an input (by the user) in previous component version and the declared input not exist in new version */ - List getPreviouslyDeclaredInputsToMerge(Component oldComponent, Component newComponent, Map> properties) { + List getPreviouslyDeclaredInputsToMerge(Component oldComponent, Component newComponent, + Map> properties) { List oldInputs = oldComponent.safeGetInputs(); return getPreviouslyDeclaredInputsToMerge(oldInputs, newComponent, properties); } - public List getPreviouslyDeclaredInputsToMerge(List oldInputs, Component newComponent, Map> properties) { + public List getPreviouslyDeclaredInputsToMerge(List oldInputs, Component newComponent, + Map> properties) { Map> getInputProperties = resolveGetInputProperties(properties); List inputsToRedeclareData = buildRedeclareInputData(newComponent, getInputProperties); return findPrevDeclaredInputs(oldInputs, inputsToRedeclareData); @@ -59,9 +59,9 @@ public class DeclaredInputsResolver { private List buildRedeclareInputData(Component newComponent, Map> getInputProperties) { Map inputsById = MapUtil.toMap(newComponent.getInputs(), InputDefinition::getUniqueId); List redeclareInputData = new ArrayList<>(); - getInputProperties.forEach((instanceId, getInputProps) -> redeclareInputData.addAll(findInputsToRedeclare(inputsById, instanceId, getInputProps))); + getInputProperties + .forEach((instanceId, getInputProps) -> redeclareInputData.addAll(findInputsToRedeclare(inputsById, instanceId, getInputProps))); return redeclareInputData; - } private List findPrevDeclaredInputs(List oldInputs, List inputsToRedeclareData) { @@ -74,29 +74,25 @@ public class DeclaredInputsResolver { return inputsToRedeclare; } - private List findInputsToRedeclare(Map inputsById, String instanceId, List getInputProps) { + private List findInputsToRedeclare(Map inputsById, String instanceId, + List getInputProps) { List redeclareInputDataList = new ArrayList<>(); getInputProps.forEach(property -> { List inputsToRedeclareIds = findInputsToRedeclareIds(inputsById, property); - RedeclareInputData redeclareInputData = new RedeclareInputData(property.getUniqueId(), inputsToRedeclareIds, instanceId, property.getDefaultValue()); + RedeclareInputData redeclareInputData = new RedeclareInputData(property.getUniqueId(), inputsToRedeclareIds, instanceId, + property.getDefaultValue()); redeclareInputDataList.add(redeclareInputData); }); return redeclareInputDataList; } private List prepareInputsForRedeclaration(Map oldInputsById, RedeclareInputData redeclareInputData) { - List inputsForRedeclaration = redeclareInputData.declaredInputIds.stream() - .filter(oldInputsById::containsKey) - .map(oldInputsById::get) - .filter(Objects::nonNull) - .map(InputDefinition::new) - .collect(Collectors.toList()); - + List inputsForRedeclaration = redeclareInputData.declaredInputIds.stream().filter(oldInputsById::containsKey) + .map(oldInputsById::get).filter(Objects::nonNull).map(InputDefinition::new).collect(Collectors.toList()); inputsForRedeclaration.forEach(input -> { input.setPropertyId(redeclareInputData.propertyId); input.setInstanceUniqueId(redeclareInputData.propertyOwnerId); - - if(!Strings.isNullOrEmpty(redeclareInputData.value)) { + if (!Strings.isNullOrEmpty(redeclareInputData.value)) { input.setValue(redeclareInputData.value); input.setDefaultValue(redeclareInputData.value); } @@ -106,10 +102,8 @@ public class DeclaredInputsResolver { private List findInputsToRedeclareIds(Map inputsById, PropertyDataDefinition property) { List getInputValues = property.getGetInputValues(); - return getInputValues.stream() - .filter(getInputVal -> isGetInputValueHasNoCorrespondingInput(getInputVal, inputsById)) - .map(GetInputValueDataDefinition::getInputId) - .collect(Collectors.toList()); + return getInputValues.stream().filter(getInputVal -> isGetInputValueHasNoCorrespondingInput(getInputVal, inputsById)) + .map(GetInputValueDataDefinition::getInputId).collect(Collectors.toList()); } private boolean isGetInputValueHasNoCorrespondingInput(GetInputValueDataDefinition getInputVal, Map inputsById) { @@ -117,6 +111,7 @@ public class DeclaredInputsResolver { } private class RedeclareInputData { + private String propertyId; private List declaredInputIds; private String propertyOwnerId; @@ -128,6 +123,5 @@ public class DeclaredInputsResolver { this.propertyOwnerId = propertyOwnerId; this.value = value; } - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.java index 91c6ff05b3..4f63dd4ab0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.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. @@ -17,9 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.input; +import static java.util.stream.Collectors.toMap; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.LAST_COMMAND; +import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.convertListOfProperties; + +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand; import org.openecomp.sdc.be.components.merge.GlobalInputsFilteringBusinessLogic; @@ -31,14 +37,6 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.springframework.core.annotation.Order; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - -import static java.util.stream.Collectors.toMap; -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.LAST_COMMAND; -import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.convertListOfProperties; - @org.springframework.stereotype.Component @Order(LAST_COMMAND) public class GlobalInputsMergeCommand extends InputsMergeCommand implements ComponentsGlobalMergeCommand { @@ -46,7 +44,9 @@ public class GlobalInputsMergeCommand extends InputsMergeCommand implements Comp private GlobalInputsFilteringBusinessLogic globalInputsFilteringBusinessLogic; private ExceptionUtils exceptionUtils; - public GlobalInputsMergeCommand(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, GlobalInputsFilteringBusinessLogic globalInputsFilteringBusinessLogic, ExceptionUtils exceptionUtils) { + public GlobalInputsMergeCommand(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, + ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, + GlobalInputsFilteringBusinessLogic globalInputsFilteringBusinessLogic, ExceptionUtils exceptionUtils) { super(inputsValuesMergingBusinessLogic, declaredInputsResolver, toscaOperationFacade, componentsUtils); this.globalInputsFilteringBusinessLogic = globalInputsFilteringBusinessLogic; this.exceptionUtils = exceptionUtils; @@ -69,12 +69,9 @@ public class GlobalInputsMergeCommand extends InputsMergeCommand implements Comp @Override Map> getProperties(Component component) { - return Stream.of(component.safeGetUiComponentInstancesProperties(), - component.safeGetUiComponentInstancesInputs(), - component.safeGetGroupsProperties(), - component.safeGetPolicyProperties()) - .flatMap(map -> map.entrySet().stream()) - .collect(toMap(Map.Entry::getKey, entry -> convertListOfProperties(entry.getValue()))); + return Stream + .of(component.safeGetUiComponentInstancesProperties(), component.safeGetUiComponentInstancesInputs(), component.safeGetGroupsProperties(), + component.safeGetPolicyProperties()).flatMap(map -> map.entrySet().stream()) + .collect(toMap(Map.Entry::getKey, entry -> convertListOfProperties(entry.getValue()))); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.java index 0f6c89a592..ba3e600e18 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.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. @@ -17,9 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.input; +import static java.util.Collections.emptyList; +import static org.apache.commons.collections.CollectionUtils.isEmpty; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -28,23 +33,16 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static java.util.Collections.emptyList; -import static org.apache.commons.collections.CollectionUtils.isEmpty; - public abstract class InputsMergeCommand { private static final Logger log = Logger.getLogger(InputsMergeCommand.class); - private InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic; private DeclaredInputsResolver declaredInputsResolver; private ToscaOperationFacade toscaOperationFacade; private ComponentsUtils componentsUtils; - public InputsMergeCommand(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { + public InputsMergeCommand(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, + ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { this.inputsValuesMergingBusinessLogic = inputsValuesMergingBusinessLogic; this.declaredInputsResolver = declaredInputsResolver; this.toscaOperationFacade = toscaOperationFacade; @@ -65,26 +63,26 @@ public abstract class InputsMergeCommand { return updateInputs(currComponent.getUniqueId(), mergedInputs); } - - private List mergeInputsValues(Component prevComponent, Component currComponent) { - log.debug("#mergeInputsValues - merge inputs values from previous component {} to current component {}", prevComponent.getUniqueId(), currComponent.getUniqueId()); + log.debug("#mergeInputsValues - merge inputs values from previous component {} to current component {}", prevComponent.getUniqueId(), + currComponent.getUniqueId()); List inputsToMerge = getInputsToMerge(currComponent); List prevInputs = prevComponent.safeGetInputs(); inputsValuesMergingBusinessLogic.mergeComponentInputs(prevInputs, inputsToMerge); return inputsToMerge; } - private List getUniquePreviouslyDeclaredInputsToMerge(Component prevComponent, Component currComponent, List mergedInputs) { + private List getUniquePreviouslyDeclaredInputsToMerge(Component prevComponent, Component currComponent, + List mergedInputs) { List previouslyDeclaredInputsToMerge = getPreviouslyDeclaredInputsToMerge(prevComponent, currComponent); return previouslyDeclaredInputsToMerge.stream() - .filter(prev -> mergedInputs.stream() - .noneMatch(merged -> merged.getName().equals(prev.getName()))).collect(Collectors.toList()); + .filter(prev -> mergedInputs.stream().noneMatch(merged -> merged.getName().equals(prev.getName()))).collect(Collectors.toList()); } - private List getPreviouslyDeclaredInputsToMerge(Component prevComponent, Component currComponent) { - log.debug("#getPreviouslyDeclaredInputsToMerge - getting inputs that were previously declared from previous component {} and setting on current component {}", prevComponent.getUniqueId(), currComponent.getUniqueId()); + log.debug( + "#getPreviouslyDeclaredInputsToMerge - getting inputs that were previously declared from previous component {} and setting on current component {}", + prevComponent.getUniqueId(), currComponent.getUniqueId()); if (isEmpty(prevComponent.getInputs())) { return emptyList(); } @@ -95,8 +93,6 @@ public abstract class InputsMergeCommand { private ActionStatus updateInputs(String containerId, List inputsToUpdate) { log.debug("#updateInputs - updating inputs for container {}", containerId); return toscaOperationFacade.updateInputsToComponent(inputsToUpdate, containerId) - .either(updatedInputs -> ActionStatus.OK, - componentsUtils::convertFromStorageResponse); + .either(updatedInputs -> ActionStatus.OK, componentsUtils::convertFromStorageResponse); } - } 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 d3214fbcd9..83a2934746 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 @@ -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. @@ -17,15 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.input; +import java.util.List; +import java.util.Map; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.model.InputDefinition; -import java.util.List; -import java.util.Map; @org.springframework.stereotype.Component public class InputsValuesMergingBusinessLogic { @@ -33,15 +32,16 @@ public class InputsValuesMergingBusinessLogic { * Merge old inputs values into the updated inputs */ public void mergeComponentInputs(List oldInputs, List inputsToMerge) { - Map oldInputsByName = MapUtil.toMap(oldInputs, InputDefinition::getName); + Map oldInputsByName = MapUtil.toMap(oldInputs, InputDefinition::getName); Map inputsToMergeByName = MapUtil.toMap(inputsToMerge, InputDefinition::getName); mergeComponentInputs(oldInputsByName, inputsToMergeByName); } - + /** - * Merge old inputs values into the updated inputs - * An input value is merged if the input previous version had a user defined value and its value is empty in current version - * @param oldInputs the currently persisted inputs mapped by their names + * Merge old inputs values into the updated inputs An input value is merged if the input previous version had a user defined value and its value + * is empty in current version + * + * @param oldInputs the currently persisted inputs mapped by their names * @param updatedInputs the currently being update inputs mapped by their names */ public void mergeComponentInputs(Map oldInputs, Map updatedInputs) { @@ -69,6 +69,4 @@ public class InputsValuesMergingBusinessLogic { private boolean isNonEmptyDefaultValue(InputDefinition input) { return input != null && !isEmptyDefaultValue(input); } - - } 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 index daf20f8c9a..912cb42664 100644 --- 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 @@ -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. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; + import fj.data.Either; +import java.util.List; +import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand; import org.openecomp.sdc.be.components.merge.capability.CapabilityResolver; @@ -37,23 +40,19 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.core.annotation.Order; -import java.util.List; -import java.util.Map; - -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; - @org.springframework.stereotype.Component @Order(ANY_ORDER_COMMAND) public class ComponentCapabilitiesPropertiesMergeBL implements VspComponentsMergeCommand { private static final Logger log = Logger.getLogger(ComponentCapabilitiesPropertiesMergeBL.class); - private final DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic; private final ToscaOperationFacade toscaOperationFacade; private final ComponentsUtils componentsUtils; private final CapabilityResolver capabilityResolver; - public ComponentCapabilitiesPropertiesMergeBL(DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, CapabilityResolver capabilityResolver) { + public ComponentCapabilitiesPropertiesMergeBL(DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic, + ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, + CapabilityResolver capabilityResolver) { this.dataDefinitionsValuesMergingBusinessLogic = dataDefinitionsValuesMergingBusinessLogic; this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; @@ -68,16 +67,17 @@ public class ComponentCapabilitiesPropertiesMergeBL implements VspComponentsMerg @Override public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { StorageOperationStatus mergeStatus = getCmptWithCapabilitiesProps(currentComponent.getUniqueId()) - .either(currCmptWithCap -> mergeCmptCalculatedCapabilitiesProperties(prevComponent, currCmptWithCap), - err -> err); + .either(currCmptWithCap -> mergeCmptCalculatedCapabilitiesProperties(prevComponent, currCmptWithCap), err -> err); return componentsUtils.convertFromStorageResponse(mergeStatus); } - public ActionStatus mergeComponentInstanceCapabilities(Component currentComponent, Component origInstanceCmpt, String instanceId, List prevInstanceCapabilities) { + 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); + Map oldToNewCap = capabilityResolver + .resolvePrevCapToNewCapability(currentComponent, origInstanceCmpt, instanceId, prevInstanceCapabilities); oldToNewCap.forEach(this::mergeCapabilityProperties); StorageOperationStatus updateStatus = updateInstanceCapabilitiesProperties(currentComponent, instanceId); return componentsUtils.convertFromStorageResponse(updateStatus); @@ -94,7 +94,8 @@ public class ComponentCapabilitiesPropertiesMergeBL implements VspComponentsMerg private void mergeInstanceCapabilities(ComponentInstance prevInstance, Component currComponent) { ComponentInstance currInstance = MapUtil.toMap(currComponent.getComponentInstances(), ComponentInstance::getName).get(prevInstance.getName()); - Map oldToNewCapabilities = capabilityResolver.resolvePrevCapIdToNewCapability(prevInstance, currInstance); + Map oldToNewCapabilities = capabilityResolver + .resolvePrevCapIdToNewCapability(prevInstance, currInstance); oldToNewCapabilities.forEach(this::mergeCapabilityProperties); } @@ -116,13 +117,9 @@ public class ComponentCapabilitiesPropertiesMergeBL implements VspComponentsMerg propertiesCapabilitiesFilter.setIgnoreComponentInstances(false); propertiesCapabilitiesFilter.setIgnoreCapabilities(false); propertiesCapabilitiesFilter.setIgnoreGroups(false); - return toscaOperationFacade.getToscaElement(cmptId, propertiesCapabilitiesFilter) - .right() - .map(err -> { - log.debug("failed to fetch cmpt {} with properties capabilities. status: {}", cmptId, err); - return err; - }); - + return toscaOperationFacade.getToscaElement(cmptId, propertiesCapabilitiesFilter).right().map(err -> { + log.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 f68019c75d..4d885180a2 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 @@ -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. @@ -17,9 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -31,12 +35,6 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.springframework.beans.factory.annotation.Autowired; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - /** * Created by chaya on 9/20/2017. */ @@ -45,31 +43,29 @@ public class ComponentInstanceArtifactsMerge implements ComponentInstanceMergeIn @Autowired ToscaOperationFacade toscaOperationFacade; - @Autowired ArtifactsBusinessLogic artifactsBusinessLogic; @Override - public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, + Component originComponent) { Map componentInstancesDeploymentArtifacts = currentResourceInstance.safeGetDeploymentArtifacts(); Map originalComponentDeploymentArtifacts = originComponent.getDeploymentArtifacts(); - Map deploymentArtifactsCreatedOnTheInstance = componentInstancesDeploymentArtifacts.entrySet() - .stream() - .filter(i -> !originalComponentDeploymentArtifacts.containsKey(i.getKey())) - .filter(i -> !ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(i.getValue().getArtifactType())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - + Map deploymentArtifactsCreatedOnTheInstance = componentInstancesDeploymentArtifacts.entrySet().stream() + .filter(i -> !originalComponentDeploymentArtifacts.containsKey(i.getKey())) + .filter(i -> !ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(i.getValue().getArtifactType())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); dataHolder.setOrigComponentDeploymentArtifactsCreatedOnTheInstance(deploymentArtifactsCreatedOnTheInstance); // dataHolder.setComponentInstanceDeploymentArtifactsTimeOut(componentInstancesDeploymentArtifacts.entrySet().stream() + // .collect(Collectors.toMap(Map.Entry::getKey, artifact -> artifact.getValue().getTimeout()))); dataHolder.setComponentInstanceDeploymentArtifactsTimeOut(componentInstancesDeploymentArtifacts.entrySet().stream() - .collect(HashMap::new, (map,entry) -> map.put(entry.getKey(), entry.getValue().getTimeout()) ,HashMap::putAll)); + .collect(HashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue().getTimeout()), HashMap::putAll)); Map componentInstancesInformationalArtifacts = currentResourceInstance.safeGetArtifacts(); Map originalComponentInformationalArtifacts = originComponent.getArtifacts(); - Map informationalArtifactsCreatedOnTheInstance = componentInstancesInformationalArtifacts.entrySet() - .stream() - .filter(i -> !originalComponentInformationalArtifacts.containsKey(i.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + Map informationalArtifactsCreatedOnTheInstance = componentInstancesInformationalArtifacts.entrySet().stream() + .filter(i -> !originalComponentInformationalArtifacts.containsKey(i.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); dataHolder.setOrigComponentInformationalArtifactsCreatedOnTheInstance(informationalArtifactsCreatedOnTheInstance); } @@ -79,47 +75,49 @@ public class ComponentInstanceArtifactsMerge implements ComponentInstanceMergeIn @Override public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { - Map origInstanceDeploymentArtifactsCreatedOnTheInstance = dataHolder.getOrigComponentDeploymentArtifactsCreatedOnTheInstance(); - Map currentInstanceDeploymentArtifacts = updatedContainerComponent.safeGetComponentInstanceDeploymentArtifacts(newInstanceId); - Map filteredDeploymentArtifactsToAdd = Optional.ofNullable(origInstanceDeploymentArtifactsCreatedOnTheInstance).orElse(new HashMap<>()).entrySet().stream() - .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceDeploymentArtifacts)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - Map updatedTimeOutDeploymentArtifacts = getUpdatedTimeOutDeploymentArtifacts(dataHolder, currentInstanceDeploymentArtifacts); - Map origInstanceInformationalArtifactsCreatedOnTheInstance = dataHolder.getOrigComponentInformationalArtifactsCreatedOnTheInstance(); - Map currentInstanceInformationalArtifacts = updatedContainerComponent.safeGetComponentInstanceInformationalArtifacts(newInstanceId); - Map filteredInformationalArtifactsToAdd = Optional.ofNullable(origInstanceInformationalArtifactsCreatedOnTheInstance).orElse(new HashMap<>()).entrySet().stream() - .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceInformationalArtifacts)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + Map origInstanceDeploymentArtifactsCreatedOnTheInstance = dataHolder + .getOrigComponentDeploymentArtifactsCreatedOnTheInstance(); + Map currentInstanceDeploymentArtifacts = updatedContainerComponent + .safeGetComponentInstanceDeploymentArtifacts(newInstanceId); + Map filteredDeploymentArtifactsToAdd = Optional.ofNullable(origInstanceDeploymentArtifactsCreatedOnTheInstance) + .orElse(new HashMap<>()).entrySet().stream() + .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceDeploymentArtifacts)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + Map updatedTimeOutDeploymentArtifacts = getUpdatedTimeOutDeploymentArtifacts(dataHolder, + currentInstanceDeploymentArtifacts); + Map origInstanceInformationalArtifactsCreatedOnTheInstance = dataHolder + .getOrigComponentInformationalArtifactsCreatedOnTheInstance(); + Map currentInstanceInformationalArtifacts = updatedContainerComponent + .safeGetComponentInstanceInformationalArtifacts(newInstanceId); + Map filteredInformationalArtifactsToAdd = Optional + .ofNullable(origInstanceInformationalArtifactsCreatedOnTheInstance).orElse(new HashMap<>()).entrySet().stream() + .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceInformationalArtifacts)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map allFilteredArtifactsToAdd = new HashMap<>(); allFilteredArtifactsToAdd.putAll(filteredDeploymentArtifactsToAdd); allFilteredArtifactsToAdd.putAll(updatedTimeOutDeploymentArtifacts); allFilteredArtifactsToAdd.putAll(filteredInformationalArtifactsToAdd); - - for (Map.Entry currentArtifactDefinition : allFilteredArtifactsToAdd.entrySet()) { - Map jsonForUpdateArtifact = artifactsBusinessLogic.buildJsonForUpdateArtifact( - currentArtifactDefinition.getValue().getUniqueId(), - currentArtifactDefinition.getValue().getArtifactName(), - currentArtifactDefinition.getValue().getArtifactType(), - currentArtifactDefinition.getValue().getArtifactGroupType(), - currentArtifactDefinition.getValue().getArtifactLabel(), - currentArtifactDefinition.getValue().getArtifactDisplayName(), - currentArtifactDefinition.getValue().getDescription(), - currentArtifactDefinition.getValue().getPayloadData(), - null, currentArtifactDefinition.getValue().getListHeatParameters()); + for (Map.Entry currentArtifactDefinition : allFilteredArtifactsToAdd.entrySet()) { + Map jsonForUpdateArtifact = artifactsBusinessLogic + .buildJsonForUpdateArtifact(currentArtifactDefinition.getValue().getUniqueId(), + currentArtifactDefinition.getValue().getArtifactName(), currentArtifactDefinition.getValue().getArtifactType(), + currentArtifactDefinition.getValue().getArtifactGroupType(), currentArtifactDefinition.getValue().getArtifactLabel(), + currentArtifactDefinition.getValue().getArtifactDisplayName(), currentArtifactDefinition.getValue().getDescription(), + currentArtifactDefinition.getValue().getPayloadData(), null, currentArtifactDefinition.getValue().getListHeatParameters()); addEsIdToArtifactJson(jsonForUpdateArtifact, currentArtifactDefinition.getValue().getEsId()); - artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, - user, jsonForUpdateArtifact, new ArtifactOperationInfo( - false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.LINK), currentArtifactDefinition.getValue()); + artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, jsonForUpdateArtifact, + new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.LINK), currentArtifactDefinition.getValue()); } return updatedContainerComponent; } - private Map getUpdatedTimeOutDeploymentArtifacts(DataForMergeHolder dataHolder, Map currentInstanceDeploymentArtifacts) { - return currentInstanceDeploymentArtifacts.entrySet().stream() - .filter(artifact -> Objects.isNull(artifact.getValue().getTimeout()) || !artifact.getValue().getTimeout() - .equals(dataHolder.getComponentInstanceDeploymentArtifactsTimeOut().get(artifact.getKey()))) - .collect(Collectors.toMap(Map.Entry::getKey, artifact -> mergeTimeOut(artifact.getValue(), dataHolder - .getComponentInstanceDeploymentArtifactsTimeOut().get(artifact.getKey())))); + private Map getUpdatedTimeOutDeploymentArtifacts(DataForMergeHolder dataHolder, + Map currentInstanceDeploymentArtifacts) { + return currentInstanceDeploymentArtifacts.entrySet().stream().filter( + artifact -> Objects.isNull(artifact.getValue().getTimeout()) || !artifact.getValue().getTimeout() + .equals(dataHolder.getComponentInstanceDeploymentArtifactsTimeOut().get(artifact.getKey()))).collect(Collectors + .toMap(Map.Entry::getKey, + artifact -> mergeTimeOut(artifact.getValue(), dataHolder.getComponentInstanceDeploymentArtifactsTimeOut().get(artifact.getKey())))); } private ArtifactDefinition mergeTimeOut(ArtifactDefinition artifact, Integer updatedTimeOut) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesPropertiesMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesPropertiesMerge.java index 9c845046c0..bc1aa0da26 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesPropertiesMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesPropertiesMerge.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. @@ -17,9 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import static org.apache.commons.collections.MapUtils.isNotEmpty; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -28,26 +33,21 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.User; -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 ComponentInstanceCapabilitiesPropertiesMerge implements ComponentInstanceMergeInterface { private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL; private ComponentsUtils componentsUtils; - public ComponentInstanceCapabilitiesPropertiesMerge(ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL, ComponentsUtils componentsUtils) { + public ComponentInstanceCapabilitiesPropertiesMerge(ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL, + ComponentsUtils componentsUtils) { this.capabilitiesPropertiesMergeBL = capabilitiesPropertiesMergeBL; this.componentsUtils = componentsUtils; } @Override - public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, + Component originComponent) { dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance)); dataHolder.setOrigInstanceNode(originComponent); } @@ -56,14 +56,16 @@ public class ComponentInstanceCapabilitiesPropertiesMerge implements ComponentIn public Component 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); - if(!ActionStatus.OK.equals(mergeStatus)){ + ActionStatus mergeStatus = capabilitiesPropertiesMergeBL + .mergeComponentInstanceCapabilities(updatedContainerComponent, origInstanceNode, newInstanceId, origInstanceCapabilities); + if (!ActionStatus.OK.equals(mergeStatus)) { throw new ByActionStatusComponentException(mergeStatus); } - return updatedContainerComponent; + return updatedContainerComponent; } private List getAllInstanceCapabilities(ComponentInstance currentResourceInstance) { - return isNotEmpty( currentResourceInstance.getCapabilities() ) ? currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList()) : new ArrayList<>() ; + 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 index 68851b1811..b99178df74 100644 --- 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 @@ -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. @@ -17,10 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; import fj.data.Either; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import org.javatuples.Pair; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; @@ -38,56 +44,42 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; -import java.util.Collection; -import java.util.Collections; -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 = Logger.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) { + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, + Component originComponent) { dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance)); dataHolder.setOrigInstanceNode(originComponent); dataHolder.setOrigComponentInstId(currentResourceInstance.getName()); } @Override - public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, - Component updatedContainerComponent, String newInstanceId) { + public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { if (!(updatedContainerComponent instanceof Service)) { // no need to handle forwarding paths return updatedContainerComponent; } Service service = (Service) updatedContainerComponent; ComponentInstance ci = service.getComponentInstanceById(newInstanceId).orElse(null); - if (ci == null){ + if (ci == null) { throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, newInstanceId); } Either resourceEither = toscaOperationFacade.getToscaFullElement(ci.getComponentUid()); - if (resourceEither.isRight() ) { - log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId()); + if (resourceEither.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getUniqueId()); throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceEither.right().value())); } - Component fetchedComponent = resourceEither.left().value(); - Pair, Map> pair = new ForwardingPathUtils() .updateForwardingPathOnVersionChange(service, dataHolder, fetchedComponent, newInstanceId); Map updated = pair.getValue0(); @@ -100,19 +92,16 @@ public class ComponentInstanceForwardingPathMerge implements ComponentInstanceMe if (updated != null && !updated.isEmpty()) { Service updateFPService = new Service(); updateFPService.setForwardingPaths(updated); - Service updateFPEither = serviceBusinessLogic - .updateForwardingPath(service.getUniqueId(), updateFPService, user, false); - updated.forEach((key, forwardingPathDataDefinition) -> service.getForwardingPaths().put(key,forwardingPathDataDefinition)); + Service updateFPEither = serviceBusinessLogic.updateForwardingPath(service.getUniqueId(), updateFPService, user, false); + updated.forEach((key, forwardingPathDataDefinition) -> service.getForwardingPaths().put(key, forwardingPathDataDefinition)); } return updatedContainerComponent; } - private List getAllInstanceCapabilities(ComponentInstance currentResourceInstance) { - if(currentResourceInstance.getCapabilities() == null || currentResourceInstance.getCapabilities().isEmpty()){ + if (currentResourceInstance.getCapabilities() == null || currentResourceInstance.getCapabilities().isEmpty()) { return Collections.EMPTY_LIST; } - return currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream) - .collect(Collectors.toList()); + 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 2f9943909c..309c0a9a86 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 @@ -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. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; import fj.data.Either; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo; import org.openecomp.sdc.be.components.merge.heat.HeatEnvArtifactsMergeBusinessLogic; @@ -34,9 +35,6 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; -import java.util.Map; - /** * Created by chaya on 9/20/2017. */ @@ -44,32 +42,30 @@ import java.util.Map; public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInterface { private static final Logger log = Logger.getLogger(ComponentInstanceHeatEnvMerge.class); - + @Autowired + protected ComponentsUtils componentsUtils; @Autowired private ArtifactsBusinessLogic artifactsBusinessLogic; - @Autowired private HeatEnvArtifactsMergeBusinessLogic heatEnvArtifactsMergeBusinessLogic; - @Autowired - protected ComponentsUtils componentsUtils; - - @Override - public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { - dataHolder.setOrigComponentInstanceHeatEnvArtifacts(containerComponent.safeGetComponentInstanceHeatArtifacts(currentResourceInstance.getUniqueId())); + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, + Component originComponent) { + dataHolder.setOrigComponentInstanceHeatEnvArtifacts( + containerComponent.safeGetComponentInstanceHeatArtifacts(currentResourceInstance.getUniqueId())); } @Override public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { List origCompInstHeatEnvArtifacts = dataHolder.getOrigComponentInstanceHeatEnvArtifacts(); List newCompInstHeatEnvArtifacts = updatedContainerComponent.safeGetComponentInstanceHeatArtifacts(newInstanceId); - List artifactsToUpdate = heatEnvArtifactsMergeBusinessLogic.mergeInstanceHeatEnvArtifacts(origCompInstHeatEnvArtifacts, newCompInstHeatEnvArtifacts); - + List artifactsToUpdate = heatEnvArtifactsMergeBusinessLogic + .mergeInstanceHeatEnvArtifacts(origCompInstHeatEnvArtifacts, newCompInstHeatEnvArtifacts); for (ArtifactDefinition artifactInfo : artifactsToUpdate) { - Map json = artifactsBusinessLogic.buildJsonForUpdateArtifact(artifactInfo, ArtifactGroupTypeEnum.DEPLOYMENT, null); - - Either uploadArtifactToService = artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, json, + Map json = artifactsBusinessLogic.buildJsonForUpdateArtifact(artifactInfo, ArtifactGroupTypeEnum.DEPLOYMENT, null); + Either uploadArtifactToService = artifactsBusinessLogic + .updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, json, new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE), null); } return updatedContainerComponent; 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 index 3058835801..d8b5020046 100644 --- 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 @@ -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. @@ -17,10 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; + import fj.data.Either; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand; import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -33,13 +38,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.core.annotation.Order; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; - @org.springframework.stereotype.Component @Order(ANY_ORDER_COMMAND) public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand { @@ -48,7 +46,8 @@ public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand private final ComponentsUtils componentsUtils; private final DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; - public ComponentInstanceInputsMergeBL(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) { + public ComponentInstanceInputsMergeBL(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, + DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) { this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; this.propertyValuesMergingBusinessLogic = propertyValuesMergingBusinessLogic; @@ -60,7 +59,8 @@ public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand if (componentInstancesInputs == null) { return ActionStatus.OK; } - componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(prevComponent, currentComponent, instanceId, instInputs)); + componentInstancesInputs + .forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(prevComponent, currentComponent, instanceId, instInputs)); return updateComponentInstancesInputs(currentComponent, componentInstancesInputs); } @@ -69,31 +69,27 @@ public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand return "merge component instance inputs"; } - public ActionStatus mergeComponentInstanceInputs(List oldInstProps, List oldInputs, Component newComponent, String instanceId) { + public ActionStatus mergeComponentInstanceInputs(List oldInstProps, List oldInputs, + Component newComponent, String instanceId) { List newInstInputs = newComponent.safeGetComponentInstanceInput(instanceId); if (newInstInputs == null) { return ActionStatus.OK; } - List oldRedeclaredInputs = findComponentInputs(oldInstProps); - oldRedeclaredInputs.forEach(oldInput -> newInstInputs.stream() - .filter(newInstInput -> oldInput.getName().equals(newInstInput.getName())) - .forEach(this::switchValues)); - + oldRedeclaredInputs.forEach( + oldInput -> newInstInputs.stream().filter(newInstInput -> oldInput.getName().equals(newInstInput.getName())).forEach(this::switchValues)); propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstInputs, newComponent.getInputs()); return updateComponentInstanceInputs(newComponent, instanceId, newInstInputs); } - + private void switchValues(ComponentInstanceInput input) { String tempDefaultValue = input.getDefaultValue(); input.setDefaultValue(input.getValue()); input.setValue(tempDefaultValue); } - + private List findComponentInputs(List oldInstProps) { - return oldInstProps.stream() - .filter(ComponentInstanceInput::isGetInputProperty) - .collect(Collectors.toList()); + return oldInstProps.stream().filter(ComponentInstanceInput::isGetInputProperty).collect(Collectors.toList()); } private ActionStatus updateComponentInstanceInputs(Component newComponent, String instanceId, List newInstInput) { @@ -105,18 +101,20 @@ public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand } private ActionStatus updateComponentInstancesInputs(Component component, Map> componentInstancesInputs) { - Either>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstanceInputsToComponent(componentInstancesInputs, component.getUniqueId()); + 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) { + 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 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/ComponentInstanceInputsRedeclareHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandler.java index 14c1ad2e9f..a026f18bd1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandler.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. @@ -17,9 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import static java.util.Collections.singletonMap; +import static java.util.stream.Collectors.toList; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap; +import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.resolveGetInputProperties; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; import org.openecomp.sdc.be.components.merge.input.DeclaredInputsResolver; import org.openecomp.sdc.be.components.merge.input.InputsValuesMergingBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -32,17 +41,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.utils.ComponentUtilities; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - -import static java.util.Collections.singletonMap; -import static java.util.stream.Collectors.toList; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap; -import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.resolveGetInputProperties; - @org.springframework.stereotype.Component public class ComponentInstanceInputsRedeclareHandler { @@ -51,55 +49,59 @@ public class ComponentInstanceInputsRedeclareHandler { private final ToscaOperationFacade toscaOperationFacade; private final ComponentsUtils componentsUtils; private final InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic; - - public ComponentInstanceInputsRedeclareHandler(DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic) { + + public ComponentInstanceInputsRedeclareHandler(DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, + ComponentsUtils componentsUtils, + InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic) { this.declaredInputsResolver = declaredInputsResolver; this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; this.inputsValuesMergingBusinessLogic = inputsValuesMergingBusinessLogic; } - ActionStatus redeclareComponentInputsForInstance(Component container, String newInstanceId, Component newInstanceOriginType, List oldInputs) { - log.debug("#redeclareComponentInputsForInstance - getting inputs that were previously declared from instance {} and setting on current component {}", newInstanceId, container.getUniqueId()); + ActionStatus redeclareComponentInputsForInstance(Component container, String newInstanceId, Component newInstanceOriginType, + List oldInputs) { + log.debug( + "#redeclareComponentInputsForInstance - getting inputs that were previously declared from instance {} and setting on current component {}", + newInstanceId, container.getUniqueId()); Map> allPropertiesForInstance = getAllGetPropertiesForInstance(container, newInstanceId); - List previouslyDeclaredInputs = declaredInputsResolver.getPreviouslyDeclaredInputsToMerge(oldInputs, container, allPropertiesForInstance); + List previouslyDeclaredInputs = declaredInputsResolver + .getPreviouslyDeclaredInputsToMerge(oldInputs, container, allPropertiesForInstance); inputsValuesMergingBusinessLogic.mergeComponentInputs(oldInputs, previouslyDeclaredInputs); Map> getInputProperties = resolveGetInputProperties(allPropertiesForInstance); updateInputsAnnotations(getInputProperties.get(newInstanceId), newInstanceOriginType, previouslyDeclaredInputs); - return updateInputs(container.getUniqueId(), previouslyDeclaredInputs); } - private void updateInputsAnnotations(List instanceProps, Component newInstanceOriginType, List previouslyDeclaredInputs) { + private void updateInputsAnnotations(List instanceProps, Component newInstanceOriginType, + List previouslyDeclaredInputs) { Map instancePropsById = toMap(instanceProps, PropertyDataDefinition::getUniqueId); for (InputDefinition input : previouslyDeclaredInputs) { - List originPropInputAnnotations = getAnnotationsFromOriginType(newInstanceOriginType, input.getPropertyId(), instancePropsById); - if(!isEmpty(originPropInputAnnotations)){ + List originPropInputAnnotations = getAnnotationsFromOriginType(newInstanceOriginType, input.getPropertyId(), + instancePropsById); + if (!isEmpty(originPropInputAnnotations)) { input.setAnnotations(originPropInputAnnotations); } } } - private List getAnnotationsFromOriginType(Component originType, String propertyId, Map instancePropsById) { + private List getAnnotationsFromOriginType(Component originType, String propertyId, + Map instancePropsById) { PropertyDataDefinition instanceProp = instancePropsById.get(propertyId); String originPropInputName = instanceProp.getName(); return ComponentUtilities.getInputAnnotations(originType, originPropInputName); } private Map> getAllGetPropertiesForInstance(Component newComponent, String instanceId) { - List allInstanceProps = Stream.of(newComponent.safeGetComponentInstanceProperties(instanceId), - newComponent.safeGetComponentInstanceInput(instanceId)) - .flatMap(Collection::stream) - .map(PropertyDataDefinition::new) - .collect(toList()); + List allInstanceProps = Stream + .of(newComponent.safeGetComponentInstanceProperties(instanceId), newComponent.safeGetComponentInstanceInput(instanceId)) + .flatMap(Collection::stream).map(PropertyDataDefinition::new).collect(toList()); return singletonMap(instanceId, allInstanceProps); } private ActionStatus updateInputs(String containerId, List inputsToUpdate) { log.debug("#updateInputs - updating inputs for container {}", containerId); return toscaOperationFacade.updateInputsToComponent(inputsToUpdate, containerId) - .either(updatedInputs -> ActionStatus.OK, - componentsUtils::convertFromStorageResponse); + .either(updatedInputs -> ActionStatus.OK, componentsUtils::convertFromStorageResponse); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.java index b2579b73d2..2d49eaeffe 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.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. @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; @@ -35,19 +35,17 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; - @org.springframework.stereotype.Component("ComponentInstanceInterfacesMerge") public class ComponentInstanceInterfacesMerge implements ComponentInstanceMergeInterface { @Autowired private ComponentsUtils componentsUtils; - @Autowired private ToscaOperationFacade toscaOperationFacade; @Override - public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, + Component originComponent) { dataHolder.setOrigInstanceNode(originComponent); dataHolder.setOrigComponentInstanceInterfaces(containerComponent.safeGetComponentInstanceInterfaces(currentResourceInstance.getUniqueId())); } @@ -56,42 +54,38 @@ public class ComponentInstanceInterfacesMerge implements ComponentInstanceMergeI public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { List origInstanceInterfaces = dataHolder.getOrigComponentInstanceInterfaces(); ActionStatus mergeStatus = mergeComponentInstanceInterfaces(updatedContainerComponent, newInstanceId, origInstanceInterfaces); - if (!ActionStatus.OK.equals(mergeStatus)){ + if (!ActionStatus.OK.equals(mergeStatus)) { throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(mergeStatus)); - } - else { + } else { return updatedContainerComponent; } } - private ActionStatus mergeComponentInstanceInterfaces(Component currentComponent, String instanceId, List prevInstanceInterfaces) { + private ActionStatus mergeComponentInstanceInterfaces(Component currentComponent, String instanceId, + List prevInstanceInterfaces) { if (CollectionUtils.isEmpty(prevInstanceInterfaces) || MapUtils.isEmpty(currentComponent.getComponentInstancesInterfaces())) { return ActionStatus.OK; } - - if(CollectionUtils.isEmpty(currentComponent.getComponentInstancesInterfaces().get(instanceId))){ + if (CollectionUtils.isEmpty(currentComponent.getComponentInstancesInterfaces().get(instanceId))) { return ActionStatus.OK; } - - currentComponent.getComponentInstancesInterfaces().get(instanceId).stream() - .forEach(newInterfaceDef -> newInterfaceDef.getOperationsMap().values() - .forEach(newOperationDef -> prevInstanceInterfaces.stream().filter(in -> in.getUniqueId().equals(newInterfaceDef.getUniqueId())) - .forEach(prevInterfaceDef -> prevInterfaceDef.getOperationsMap().values().stream().filter(in1 -> in1.getUniqueId().equals(newOperationDef.getUniqueId())) + currentComponent.getComponentInstancesInterfaces().get(instanceId).stream().forEach( + newInterfaceDef -> newInterfaceDef.getOperationsMap().values().forEach( + newOperationDef -> prevInstanceInterfaces.stream().filter(in -> in.getUniqueId().equals(newInterfaceDef.getUniqueId())).forEach( + prevInterfaceDef -> prevInterfaceDef.getOperationsMap().values().stream() + .filter(in1 -> in1.getUniqueId().equals(newOperationDef.getUniqueId())) .forEach(oldOperationDef -> mergeOperationInputDefinitions(oldOperationDef.getInputs(), newOperationDef.getInputs()))))); - StorageOperationStatus updateStatus = toscaOperationFacade.updateComponentInstanceInterfaces(currentComponent, instanceId); return componentsUtils.convertFromStorageResponse(updateStatus); } - - private void mergeOperationInputDefinitions(ListDataDefinition origInputs, ListDataDefinition newInputs){ + private void mergeOperationInputDefinitions(ListDataDefinition origInputs, + ListDataDefinition newInputs) { newInputs.getListToscaDataDefinition() - .forEach(inp -> origInputs.getListToscaDataDefinition().stream().filter(in -> in.getInputId().equals(inp.getInputId())) - .forEach(in -> { - inp.setSourceProperty(in.getSourceProperty()); - inp.setSource(in.getSource()); - inp.setValue(in.getValue()); - })); + .forEach(inp -> origInputs.getListToscaDataDefinition().stream().filter(in -> in.getInputId().equals(inp.getInputId())).forEach(in -> { + inp.setSourceProperty(in.getSourceProperty()); + inp.setSource(in.getSource()); + inp.setValue(in.getValue()); + })); } - } 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 888ad2b71c..7353a1205f 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 @@ -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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; import fj.data.Either; +import java.util.List; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -34,8 +34,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; -import java.util.List; - /** * Created by chaya on 9/12/2017. */ @@ -43,14 +41,11 @@ import java.util.List; public class ComponentInstanceMergeDataBusinessLogic { private static final Logger log = Logger.getLogger(ComponentInstanceMergeDataBusinessLogic.class); - @Autowired @Lazy private List componentInstancesMergeBLs; - @Autowired private ToscaOperationFacade toscaOperationFacade; - @Autowired private ComponentsUtils componentsUtils; @@ -61,10 +56,12 @@ public class ComponentInstanceMergeDataBusinessLogic { /** * Saves all containerComponents data before deleting, in order to merge once creating a new instance + * * @param containerComponent * @param currentResourceInstance */ - public DataForMergeHolder saveAllDataBeforeDeleting(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + public DataForMergeHolder saveAllDataBeforeDeleting(org.openecomp.sdc.be.model.Component containerComponent, + ComponentInstance currentResourceInstance, Component originComponent) { DataForMergeHolder dataHolder = new DataForMergeHolder(); for (ComponentInstanceMergeInterface compInstMergeBL : componentInstancesMergeBLs) { compInstMergeBL.saveDataBeforeMerge(dataHolder, containerComponent, currentResourceInstance, originComponent); @@ -74,14 +71,16 @@ public class ComponentInstanceMergeDataBusinessLogic { /** * Merges inputs and instance inputs/props of the new Container component with the old container component data (before deleting) + * * @param containerComponent * @param newContainerComponentId * @param newInstanceId * @return */ - public Component mergeComponentUserOrigData(User user, DataForMergeHolder dataHolder, org.openecomp.sdc.be.model.Component containerComponent, String newContainerComponentId, String newInstanceId) { - - Either componentWithInstancesInputsAndProperties = getComponentWithInstancesMergeEntities(newContainerComponentId); + public Component mergeComponentUserOrigData(User user, DataForMergeHolder dataHolder, org.openecomp.sdc.be.model.Component containerComponent, + String newContainerComponentId, String newInstanceId) { + Either componentWithInstancesInputsAndProperties = getComponentWithInstancesMergeEntities( + newContainerComponentId); if (componentWithInstancesInputsAndProperties.isRight()) { log.error("Component with id {} was not found", newContainerComponentId); StorageOperationStatus storageOperationStatus = componentWithInstancesInputsAndProperties.right().value(); @@ -89,7 +88,7 @@ public class ComponentInstanceMergeDataBusinessLogic { throw new ByActionStatusComponentException(actionStatus); } Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value(); - componentInstancesMergeBLs.forEach(c-> c.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, newInstanceId)); + componentInstancesMergeBLs.forEach(c -> c.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, newInstanceId)); return updatedContainerComponent; } 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 29ce663fe3..3cac6567a3 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; import org.openecomp.sdc.be.model.Component; @@ -29,7 +28,8 @@ import org.openecomp.sdc.be.model.User; */ public interface ComponentInstanceMergeInterface { - void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent); + void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, + Component originComponent); Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId); } 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 index 8a0b628c2d..e6205a236d 100644 --- 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 @@ -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. @@ -17,10 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; + import fj.data.Either; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand; import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -33,14 +39,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.core.annotation.Order; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; - @org.springframework.stereotype.Component @Order(ANY_ORDER_COMMAND) public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCommand { @@ -49,12 +47,26 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom private final ComponentsUtils componentsUtils; private final DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; - public ComponentInstancePropertiesMergeBL(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) { + public ComponentInstancePropertiesMergeBL(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, + DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) { this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; this.propertyValuesMergingBusinessLogic = propertyValuesMergingBusinessLogic; } + private static Map getComponentNameByUniqueId(Component component) { + return asMap(component, ComponentInstance::getUniqueId, ComponentInstance::getName); + } + + private static Map getComponentUniqueIdByName(Component component) { + return asMap(component, ComponentInstance::getName, ComponentInstance::getUniqueId); + } + + private static Map asMap(Component component, Function keyMapper, + Function valueMapper) { + return component.safeGetComponentInstances().stream().collect(Collectors.toMap(keyMapper, valueMapper)); + } + @Override public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { Map> newInstProps = currentComponent.getComponentInstancesProperties(); @@ -63,11 +75,9 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom } Map currComponentNames = getComponentNameByUniqueId(currentComponent); Map prevComponentUniqueIds = getComponentUniqueIdByName(prevComponent); - newInstProps.forEach((instanceId, newProps) -> { String instanceName = currComponentNames.get(instanceId); String oldInstanceId = prevComponentUniqueIds.get(instanceName); - mergeOldInstancePropertiesValues(prevComponent, currentComponent, oldInstanceId, newProps); }); return updateComponentInstancesProperties(currentComponent, newInstProps); @@ -78,8 +88,8 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom return "merge component instance properties"; } - - public ActionStatus mergeComponentInstanceProperties(List oldInstProps, List oldInputs, Component newComponent, String instanceId) { + public ActionStatus mergeComponentInstanceProperties(List oldInstProps, List oldInputs, + Component newComponent, String instanceId) { List newInstProps = newComponent.safeGetComponentInstanceProperties(instanceId); if (newInstProps == null) { return ActionStatus.OK; @@ -87,28 +97,18 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstProps, newComponent.getInputs()); return updateComponentInstanceProperties(newComponent, instanceId, newInstProps); } - - private static Map getComponentNameByUniqueId(Component component) { - return asMap(component, ComponentInstance::getUniqueId, ComponentInstance::getName); - } - - private static Map getComponentUniqueIdByName(Component component) { - return asMap(component, ComponentInstance::getName, ComponentInstance::getUniqueId); - } - - private static Map asMap(Component component, Function keyMapper, Function valueMapper) { - return component.safeGetComponentInstances().stream(). - collect(Collectors.toMap(keyMapper, valueMapper)); - } - private void mergeOldInstancePropertiesValues(Component oldComponent, Component newComponent, String instanceId, List newProps) { - List oldInstProperties = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceProperties(instanceId); + 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()); + Either>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade + .updateComponentInstancePropsToComponent(newInstProps, newComponent.getUniqueId()); if (mapStorageOperationStatusEither.isRight()) { return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value()); } @@ -122,5 +122,4 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom } 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 cbfc97013a..d896e4a8a0 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 @@ -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. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; + import fj.data.Either; +import java.util.ArrayList; +import java.util.List; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -35,11 +38,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.ArrayList; -import java.util.List; - -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; - /** * Created by chaya on 9/20/2017. */ @@ -47,14 +45,16 @@ import static org.apache.commons.collections.CollectionUtils.isNotEmpty; public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMergeInterface { private static final Logger log = Logger.getLogger(ComponentInstancePropsAndInputsMerge.class); - private final ToscaOperationFacade toscaOperationFacade; private final ComponentsUtils componentsUtils; private final ComponentInstancePropertiesMergeBL componentInstancePropertiesMergeBL; private final ComponentInstanceInputsMergeBL resourceInstanceInputsMergeBL; private final ComponentInstanceInputsRedeclareHandler instanceInputsRedeclareHandler; - public ComponentInstancePropsAndInputsMerge(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, ComponentInstancePropertiesMergeBL componentInstancePropertiesMergeBL, ComponentInstanceInputsMergeBL resourceInstanceInputsMergeBL, ComponentInstanceInputsRedeclareHandler instanceInputsRedeclareHandler) { + public ComponentInstancePropsAndInputsMerge(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, + ComponentInstancePropertiesMergeBL componentInstancePropertiesMergeBL, + ComponentInstanceInputsMergeBL resourceInstanceInputsMergeBL, + ComponentInstanceInputsRedeclareHandler instanceInputsRedeclareHandler) { this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; this.componentInstancePropertiesMergeBL = componentInstancePropertiesMergeBL; @@ -63,7 +63,8 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe } @Override - public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, + Component originComponent) { dataHolder.setOrigComponentInstanceInputs(containerComponent.safeGetComponentInstanceInputsByName(currentResourceInstance.getName())); dataHolder.setOrigComponentInstanceProperties(containerComponent.safeGetComponentInstanceProperties(currentResourceInstance.getUniqueId())); dataHolder.setOrigComponentInputs(containerComponent.getInputs()); @@ -71,17 +72,20 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe @Override public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { - Either, ActionStatus> instanceInputsEither = mergeComponentInstanceInputsIntoContainer(dataHolder, updatedContainerComponent, newInstanceId); + Either, ActionStatus> instanceInputsEither = mergeComponentInstanceInputsIntoContainer(dataHolder, + updatedContainerComponent, newInstanceId); if (instanceInputsEither.isRight()) { ActionStatus actionStatus = instanceInputsEither.right().value(); throw new ByActionStatusComponentException(actionStatus); } - Either, ActionStatus> instancePropsEither = mergeComponentInstancePropsIntoContainer(dataHolder, updatedContainerComponent, newInstanceId); + Either, ActionStatus> instancePropsEither = mergeComponentInstancePropsIntoContainer(dataHolder, + updatedContainerComponent, newInstanceId); if (instancePropsEither.isRight()) { ActionStatus actionStatus = instancePropsEither.right().value(); throw new ByActionStatusComponentException(actionStatus); } - Either, ActionStatus> inputsEither = mergeComponentInputsIntoContainer(dataHolder, updatedContainerComponent.getUniqueId(), newInstanceId); + Either, ActionStatus> inputsEither = mergeComponentInputsIntoContainer(dataHolder, + updatedContainerComponent.getUniqueId(), newInstanceId); if (inputsEither.isRight()) { ActionStatus actionStatus = inputsEither.right().value(); throw new ByActionStatusComponentException(actionStatus); @@ -89,12 +93,14 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe return updatedContainerComponent; } - private Either, ActionStatus> mergeComponentInstancePropsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) { + private Either, ActionStatus> mergeComponentInstancePropsIntoContainer(DataForMergeHolder dataHolder, + Component updatedComponent, + String instanceId) { List originComponentInstanceProps = dataHolder.getOrigComponentInstanceProperties(); List originComponentsInputs = dataHolder.getOrigComponentInputs(); List newComponentInstancesProps = updatedComponent.safeGetComponentInstanceProperties(instanceId); - ActionStatus actionStatus = componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(originComponentInstanceProps, originComponentsInputs, updatedComponent, instanceId); - + 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); return Either.right(actionStatus); @@ -102,11 +108,14 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe return Either.left(newComponentInstancesProps); } - private Either, ActionStatus> mergeComponentInstanceInputsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) { + private Either, ActionStatus> mergeComponentInstanceInputsIntoContainer(DataForMergeHolder dataHolder, + Component updatedComponent, + String instanceId) { List originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs(); List originComponentsInputs = dataHolder.getOrigComponentInputs(); List newComponentInstancesInputs = updatedComponent.safeGetComponentInstanceInput(instanceId); - ActionStatus actionStatus = resourceInstanceInputsMergeBL.mergeComponentInstanceInputs(originComponentInstanceInputs, originComponentsInputs, updatedComponent, 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); return Either.right(actionStatus); @@ -114,19 +123,22 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe return Either.left(newComponentInstancesInputs); } - private Either, ActionStatus> mergeComponentInputsIntoContainer(DataForMergeHolder dataHolder, String newContainerComponentId, String newInstanceId) { + private Either, ActionStatus> mergeComponentInputsIntoContainer(DataForMergeHolder dataHolder, + String newContainerComponentId, String newInstanceId) { List origComponentInputs = dataHolder.getOrigComponentInputs(); List inputsToAddToContainer = new ArrayList<>(); if (isNotEmpty(origComponentInputs)) { // get instance inputs and properties after merge - Either componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId); + Either componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties( + newContainerComponentId); if (componentWithInstancesInputsAndProperties.isRight()) { log.error("Component %s was not found", newContainerComponentId); return Either.right(componentsUtils.convertFromStorageResponse(componentWithInstancesInputsAndProperties.right().value())); } Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value(); Component currInstanceOriginType = dataHolder.getCurrInstanceNode(); - ActionStatus redeclareStatus = instanceInputsRedeclareHandler.redeclareComponentInputsForInstance(updatedContainerComponent, newInstanceId, currInstanceOriginType, origComponentInputs); + ActionStatus redeclareStatus = instanceInputsRedeclareHandler + .redeclareComponentInputsForInstance(updatedContainerComponent, newInstanceId, currInstanceOriginType, origComponentInputs); if (redeclareStatus != ActionStatus.OK) { log.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer); return 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 index 8c515a5e8b..7e25c02739 100644 --- 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 @@ -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. @@ -17,10 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; import fj.data.Either; +import java.util.Collections; +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.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.merge.utils.CapabilityOwner; @@ -38,90 +44,77 @@ import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.Collections; -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; - - @org.springframework.stereotype.Component("ComponentInstanceRelashionMerge") public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInterface { + private static final Logger log = Logger.getLogger(ComponentInstanceRelationMerge.class); - private final ComponentsUtils componentsUtils; private final MergeInstanceUtils mergeInstanceUtils; private final ToscaOperationFacade toscaOperationFacade; - public ComponentInstanceRelationMerge(ComponentsUtils componentsUtils, MergeInstanceUtils mergeInstanceUtils, ToscaOperationFacade toscaOperationFacade) { + public ComponentInstanceRelationMerge(ComponentsUtils componentsUtils, MergeInstanceUtils mergeInstanceUtils, + ToscaOperationFacade toscaOperationFacade) { this.componentsUtils = componentsUtils; this.mergeInstanceUtils = mergeInstanceUtils; this.toscaOperationFacade = toscaOperationFacade; } - @Override - public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + 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); + //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()) { - ComponentInstanceBuildingBlocks instBuildingBlocks = mergeInstanceUtils.getInstanceAtomicBuildingBlocks(currentResourceInstance, originComponent); - - if (instBuildingBlocks != null) { - List fromRelInfoList = convert(relationsFrom, rel -> mergeInstanceUtils.mapRelationRequirement(rel, instBuildingBlocks.getVfcInstances())); - List toRelInfoList = convert(relationsTo, rel -> mergeInstanceUtils.mapRelationCapability(rel, instBuildingBlocks.getCapabilitiesOwners())); - + ComponentInstanceBuildingBlocks instBuildingBlocks = mergeInstanceUtils + .getInstanceAtomicBuildingBlocks(currentResourceInstance, originComponent); + if (instBuildingBlocks != null) { + List fromRelInfoList = convert(relationsFrom, + rel -> mergeInstanceUtils.mapRelationRequirement(rel, instBuildingBlocks.getVfcInstances())); + List toRelInfoList = convert(relationsTo, + rel -> mergeInstanceUtils.mapRelationCapability(rel, instBuildingBlocks.getCapabilitiesOwners())); // Encapsulate all needed info in one container ContainerRelationsMergeInfo containerRelationsMergeInfo = new ContainerRelationsMergeInfo(fromRelInfoList, toRelInfoList); // Save it dataHolder.setVfRelationsInfo(containerRelationsMergeInfo); } - } - else { + } else { log.debug("No relations relevant to currentResourceInstance {} found in container component", currentResourceInstance); } - } - @Override public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { Wrapper> resultWrapper = new Wrapper<>(); - ContainerRelationsMergeInfo containerRelationsMergeInfo = getRelationsMergeInfo(dataHolder, updatedContainerComponent, resultWrapper); - ComponentInstance newComponentInstance = null; - if(resultWrapper.isEmpty()) { + if (resultWrapper.isEmpty()) { //Component Instance newComponentInstance = loadComponentInstance(updatedContainerComponent, newInstanceId, resultWrapper); } - - if(resultWrapper.isEmpty() && containerRelationsMergeInfo != null) { + if (resultWrapper.isEmpty() && containerRelationsMergeInfo != null) { // Load VFCI and filter them by name ComponentInstanceBuildingBlocks instanceBuildBlocks = mergeInstanceUtils.getInstanceAtomicBuildingBlocks(newComponentInstance); - if(instanceBuildBlocks != null) { + if (instanceBuildBlocks != null) { // Process Relationships - Stream toRelationsInfoStream = getCapabilitiesRelationInfoStream(updatedContainerComponent, newInstanceId, containerRelationsMergeInfo, instanceBuildBlocks); - Stream fromRelationsInfoStream = getRequirementRelationsInfoStream(updatedContainerComponent, newInstanceId, containerRelationsMergeInfo, instanceBuildBlocks); + Stream toRelationsInfoStream = getCapabilitiesRelationInfoStream(updatedContainerComponent, + newInstanceId, containerRelationsMergeInfo, instanceBuildBlocks); + Stream fromRelationsInfoStream = getRequirementRelationsInfoStream(updatedContainerComponent, + newInstanceId, containerRelationsMergeInfo, instanceBuildBlocks); List updatedRelations = getUpdatedRelations(toRelationsInfoStream, fromRelationsInfoStream); - Either, StorageOperationStatus> listStorageOperationStatusEither = toscaOperationFacade.associateResourceInstances(null, updatedContainerComponent.getUniqueId(), updatedRelations); + Either, StorageOperationStatus> listStorageOperationStatusEither = toscaOperationFacade + .associateResourceInstances(null, updatedContainerComponent.getUniqueId(), updatedRelations); if (listStorageOperationStatusEither.isLeft()) { resultWrapper.setInnerElement(Either.left(updatedContainerComponent)); - } - else { + } else { StorageOperationStatus status = listStorageOperationStatusEither.right().value(); log.debug("Failed to associate instances of resource {} status is {}", updatedContainerComponent.getUniqueId(), status); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), updatedContainerComponent.getUniqueId()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(status), updatedContainerComponent.getUniqueId()); throw new ByResponseFormatComponentException(responseFormat); } } @@ -129,26 +122,31 @@ public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInt return resultWrapper.getInnerElement().left().value(); } - private Stream getRequirementRelationsInfoStream(Component updatedContainerComponent, String newInstanceId, ContainerRelationsMergeInfo containerRelationsMergeInfo, ComponentInstanceBuildingBlocks instanceBuildBlocks) { + private Stream getRequirementRelationsInfoStream(Component updatedContainerComponent, String newInstanceId, + ContainerRelationsMergeInfo containerRelationsMergeInfo, + ComponentInstanceBuildingBlocks instanceBuildBlocks) { Map vfciMap = MapUtil.toMap(instanceBuildBlocks.getVfcInstances(), ComponentInstance::getName, (p1, p2) -> p1); List fromRelationsInfo = containerRelationsMergeInfo.getFromRelationsInfo(); Stream fromRelationsInfoStream = null; - if( fromRelationsInfo != null) { + if (fromRelationsInfo != null) { fromRelationsInfoStream = fromRelationsInfo.stream() - .map(oldReqInfo -> mergeInstanceUtils.restoreRequirementRelation(oldReqInfo, newInstanceId, vfciMap, updatedContainerComponent)) - .filter(Objects::nonNull); + .map(oldReqInfo -> mergeInstanceUtils.restoreRequirementRelation(oldReqInfo, newInstanceId, vfciMap, updatedContainerComponent)) + .filter(Objects::nonNull); } return fromRelationsInfoStream; } - private Stream getCapabilitiesRelationInfoStream(Component updatedContainerComponent, String newInstanceId, ContainerRelationsMergeInfo containerRelationsMergeInfo, ComponentInstanceBuildingBlocks instanceBuildBlocks) { - Map capOwnersByName = MapUtil.toMap(instanceBuildBlocks.getCapabilitiesOwners(), CapabilityOwner::getName, (p1, p2) -> p1); + private Stream getCapabilitiesRelationInfoStream(Component updatedContainerComponent, String newInstanceId, + ContainerRelationsMergeInfo containerRelationsMergeInfo, + ComponentInstanceBuildingBlocks instanceBuildBlocks) { + Map capOwnersByName = MapUtil + .toMap(instanceBuildBlocks.getCapabilitiesOwners(), CapabilityOwner::getName, (p1, p2) -> p1); List toRelationsInfo = containerRelationsMergeInfo.getToRelationsInfo(); Stream toRelationsInfoStream = null; if (toRelationsInfo != null) { - toRelationsInfoStream = toRelationsInfo.stream() - .map(oldCapInfo -> mergeInstanceUtils.restoreCapabilityRelation(oldCapInfo, newInstanceId, capOwnersByName, updatedContainerComponent)) - .filter(Objects::nonNull); + toRelationsInfoStream = toRelationsInfo.stream().map( + oldCapInfo -> mergeInstanceUtils.restoreCapabilityRelation(oldCapInfo, newInstanceId, capOwnersByName, updatedContainerComponent)) + .filter(Objects::nonNull); } return toRelationsInfoStream; } @@ -160,65 +158,50 @@ public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInt * @return */ private ComponentInstance loadComponentInstance(Component containerComponent, String instanceId, - Wrapper> resultWrapper) { + 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, + 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, + private List getRelations(Function getNodeFunc, Component containerComponent, ComponentInstance currentResourceInstance) { - final List componentInstancesRelations = containerComponent.getComponentInstancesRelations(); if (componentInstancesRelations == null) { return Collections.emptyList(); } - final String vfInstanceId = currentResourceInstance.getUniqueId(); - - return componentInstancesRelations.stream() - .filter(rel -> StringUtils.equals(getNodeFunc.apply(rel), vfInstanceId)) - .collect(Collectors.toList()); + return componentInstancesRelations.stream().filter(rel -> StringUtils.equals(getNodeFunc.apply(rel), vfInstanceId)) + .collect(Collectors.toList()); } - private List convert(List relationsDef, + private List convert(List relationsDef, Function mapFunc) { - return relationsDef.stream() - .map(mapFunc) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + return relationsDef.stream().map(mapFunc).filter(Objects::nonNull).collect(Collectors.toList()); } - - private ContainerRelationsMergeInfo getRelationsMergeInfo(DataForMergeHolder dataHolder, - Component updatedContainerComponent, + + private ContainerRelationsMergeInfo getRelationsMergeInfo(DataForMergeHolder dataHolder, Component updatedContainerComponent, Wrapper> resultWrapper) { ContainerRelationsMergeInfo containerRelationsMergeInfo = dataHolder.getContainerRelationsMergeInfo(); if (containerRelationsMergeInfo == null) { log.debug("There is no info about relations should be restored."); resultWrapper.setInnerElement(Either.left(updatedContainerComponent)); } - return containerRelationsMergeInfo; } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeCommand.java index 317f528ffc..da8f6fd2d0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeCommand.java @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.LAST_COMMAND; + import fj.data.Either; +import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand; import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; @@ -32,10 +34,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.core.annotation.Order; -import java.util.List; - -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.LAST_COMMAND; - @org.springframework.stereotype.Component @Order(LAST_COMMAND)//must run after all merge commands public class ComponentInstanceRelationMergeCommand implements VspComponentsMergeCommand { @@ -44,22 +42,25 @@ public class ComponentInstanceRelationMergeCommand implements VspComponentsMerge private final MergeInstanceUtils mergeInstanceUtils; private final ComponentsUtils componentsUtils; - public ComponentInstanceRelationMergeCommand(ToscaOperationFacade toscaOperationFacade, MergeInstanceUtils mergeInstanceUtils, ComponentsUtils componentsUtils) { + public ComponentInstanceRelationMergeCommand(ToscaOperationFacade toscaOperationFacade, MergeInstanceUtils mergeInstanceUtils, + ComponentsUtils componentsUtils) { this.toscaOperationFacade = toscaOperationFacade; this.mergeInstanceUtils = mergeInstanceUtils; this.componentsUtils = componentsUtils; } + @Override public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { List updatedUiRelations = mergeInstanceUtils.getUpdatedUiRelations(prevComponent, currentComponent); - if(CollectionUtils.isNotEmpty(updatedUiRelations)){ + if (CollectionUtils.isNotEmpty(updatedUiRelations)) { return associateResourceInstances(currentComponent, updatedUiRelations); } return ActionStatus.OK; } private ActionStatus associateResourceInstances(Component currentComponent, List updatedUiRelations) { - Either, StorageOperationStatus> listStorageOperationStatusEither = toscaOperationFacade.associateResourceInstances(null, currentComponent.getUniqueId(), updatedUiRelations); + Either, StorageOperationStatus> listStorageOperationStatusEither = toscaOperationFacade + .associateResourceInstances(null, currentComponent.getUniqueId(), updatedUiRelations); if (listStorageOperationStatusEither.isLeft()) { currentComponent.getComponentInstancesRelations().addAll(updatedUiRelations); } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ContainerRelationsMergeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ContainerRelationsMergeInfo.java index 565fb46047..d89b6edb09 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ContainerRelationsMergeInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ContainerRelationsMergeInfo.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. @@ -17,12 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; import java.util.List; public class ContainerRelationsMergeInfo { + private List fromRelationsInfo; private List toRelationsInfo; @@ -38,5 +38,4 @@ public class ContainerRelationsMergeInfo { public List getToRelationsInfo() { return toRelationsInfo; } - } 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 926daab1d3..623d86e8e1 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 @@ -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. @@ -17,10 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; - +import java.util.ArrayList; +import java.util.Collections; +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; @@ -29,13 +33,6 @@ import org.openecomp.sdc.be.model.ComponentInstanceInterface; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - /** * Created by chaya on 9/7/2017. */ @@ -54,7 +51,7 @@ public class DataForMergeHolder { private Component currInstanceNode; private String origComponentInstId; private List origComponentInstanceInterfaces; - private Map componentInstanceDeploymentArtifactsTimeOut; + private Map componentInstanceDeploymentArtifactsTimeOut; public DataForMergeHolder() { origComponentInstanceInputs = new ArrayList<>(); @@ -131,15 +128,19 @@ public class DataForMergeHolder { this.origComponentInputs = origComponentInputs; } - Map getOrigComponentDeploymentArtifactsCreatedOnTheInstance(){ return this.origCompInstDeploymentArtifactsCreatedOnTheInstance;} - - Map getOrigComponentInformationalArtifactsCreatedOnTheInstance(){ return origCompInstInformationalArtifactsCreatedOnTheInstance;} + Map getOrigComponentDeploymentArtifactsCreatedOnTheInstance() { + return this.origCompInstDeploymentArtifactsCreatedOnTheInstance; + } - void setOrigComponentDeploymentArtifactsCreatedOnTheInstance(Map origDeploymentArtifacts){ + void setOrigComponentDeploymentArtifactsCreatedOnTheInstance(Map origDeploymentArtifacts) { origCompInstDeploymentArtifactsCreatedOnTheInstance = origDeploymentArtifacts; } - void setOrigComponentInformationalArtifactsCreatedOnTheInstance(Map origInformationalArtifacts){ + Map getOrigComponentInformationalArtifactsCreatedOnTheInstance() { + return origCompInstInformationalArtifactsCreatedOnTheInstance; + } + + void setOrigComponentInformationalArtifactsCreatedOnTheInstance(Map origInformationalArtifacts) { origCompInstInformationalArtifactsCreatedOnTheInstance = origInformationalArtifacts; } @@ -191,14 +192,14 @@ public class DataForMergeHolder { this.origComponentInstId = origComponentInstId; } - void setComponentInstanceDeploymentArtifactsTimeOut(Map componentInstancesDeploymentArtifacts) { - this.componentInstanceDeploymentArtifactsTimeOut = componentInstancesDeploymentArtifacts; - } - public Map getComponentInstanceDeploymentArtifactsTimeOut() { return componentInstanceDeploymentArtifactsTimeOut; } + void setComponentInstanceDeploymentArtifactsTimeOut(Map componentInstancesDeploymentArtifacts) { + this.componentInstanceDeploymentArtifactsTimeOut = componentInstancesDeploymentArtifacts; + } + public List getOrigComponentInstanceInterfaces() { return origComponentInstanceInterfaces; } @@ -206,5 +207,4 @@ public class DataForMergeHolder { public void setOrigComponentInstanceInterfaces(List origComponentInstanceInterfaces) { this.origComponentInstanceInterfaces = origComponentInstanceInterfaces; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java index e0fb64325c..626db53d91 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java @@ -21,6 +21,11 @@ */ package org.openecomp.sdc.be.components.merge.instance; +import static org.apache.commons.collections.MapUtils.isEmpty; + +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Component; @@ -28,12 +33,6 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ExternalReferencesOperation; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import static org.apache.commons.collections.MapUtils.isEmpty; - @org.springframework.stereotype.Component public class ExternalRefsMergeBL implements ComponentInstanceMergeInterface { @@ -44,10 +43,10 @@ public class ExternalRefsMergeBL implements ComponentInstanceMergeInterface { } @Override - public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, - ComponentInstance currentResourceInstance, Component originComponent) { - Map> externalRefs = externalReferencesOperation.getAllExternalReferences(containerComponent.getUniqueId(), - currentResourceInstance.getUniqueId()); + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, + Component originComponent) { + Map> externalRefs = externalReferencesOperation + .getAllExternalReferences(containerComponent.getUniqueId(), currentResourceInstance.getUniqueId()); dataHolder.setOrigComponentInstanceExternalRefs(externalRefs); } @@ -55,13 +54,12 @@ public class ExternalRefsMergeBL implements ComponentInstanceMergeInterface { public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { Optional componentInstance = updatedContainerComponent.getComponentInstanceById(newInstanceId); if (!componentInstance.isPresent()) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, - newInstanceId); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, newInstanceId); } - Map> savedExternalRefs = dataHolder.getOrigCompInstExternalRefs(); + Map> savedExternalRefs = dataHolder.getOrigCompInstExternalRefs(); if (!isEmpty(savedExternalRefs)) { - externalReferencesOperation.addAllExternalReferences(updatedContainerComponent.getUniqueId(), - componentInstance.get().getUniqueId(), savedExternalRefs); + externalReferencesOperation + .addAllExternalReferences(updatedContainerComponent.getUniqueId(), componentInstance.get().getUniqueId(), savedExternalRefs); } return updatedContainerComponent; } 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 index 4297aa82a2..fcd0906e1c 100644 --- 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.instance; import lombok.AllArgsConstructor; @@ -32,5 +31,4 @@ public class RelationMergeInfo { private final String capReqName; private final String capOwnerName; private final RequirementCapabilityRelDef relDef; - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.java index c31c9fa1cd..9984e0de07 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.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. @@ -17,9 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.policy; +import static java.util.Collections.emptyList; +import static java.util.stream.Collectors.toList; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.apache.commons.collections.MapUtils.isEmpty; +import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand; import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -34,18 +44,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.core.annotation.Order; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import static java.util.Collections.emptyList; -import static java.util.stream.Collectors.toList; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.apache.commons.collections.MapUtils.isEmpty; -import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND; - @org.springframework.stereotype.Component @Order(ANY_ORDER_COMMAND) public class PoliciesMergeCommand implements ComponentsGlobalMergeCommand, VspComponentsMergeCommand { @@ -70,9 +68,11 @@ public class PoliciesMergeCommand implements ComponentsGlobalMergeCommand, VspCo } private ActionStatus associatePoliciesToComponent(Component currentComponent, Map policiesToMerge) { - log.debug("#associatePoliciesToComponent - associating {} policies into component {}", policiesToMerge.size(), currentComponent.getUniqueId()); + log.debug("#associatePoliciesToComponent - associating {} policies into component {}", policiesToMerge.size(), + currentComponent.getUniqueId()); currentComponent.setPolicies(policiesToMerge); - StorageOperationStatus associateResult = toscaOperationFacade.associatePoliciesToComponent(currentComponent.getUniqueId(), new ArrayList<>(policiesToMerge.values())); + StorageOperationStatus associateResult = toscaOperationFacade + .associatePoliciesToComponent(currentComponent.getUniqueId(), new ArrayList<>(policiesToMerge.values())); return componentsUtils.convertFromStorageResponse(associateResult); } @@ -92,7 +92,7 @@ public class PoliciesMergeCommand implements ComponentsGlobalMergeCommand, VspCo if (isEmpty(policy.getTargets())) { return; } - Map> targets = buildPolicyTargetsMap(policy, prevComponent, currComponent); + Map> targets = buildPolicyTargetsMap(policy, prevComponent, currComponent); policy.setTargets(targets); } @@ -121,34 +121,24 @@ public class PoliciesMergeCommand implements ComponentsGlobalMergeCommand, VspCo return resolveGroupTargetsByInvariantName(prevComponent, currComponent, prevGroupTargets); } - private List resolveInstanceTargetsByInstanceName(Component prevComponent, Component currComponent, List prevCompInstanceTargets) { - return prevCompInstanceTargets.stream() - .map(prevInstId -> resolveNewInstId(prevComponent, currComponent, prevInstId)) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(toList()); + private List resolveInstanceTargetsByInstanceName(Component prevComponent, Component currComponent, + List prevCompInstanceTargets) { + return prevCompInstanceTargets.stream().map(prevInstId -> resolveNewInstId(prevComponent, currComponent, prevInstId)) + .filter(Optional::isPresent).map(Optional::get).collect(toList()); } private List resolveGroupTargetsByInvariantName(Component prevComponent, Component currComponent, List prevGroupTargets) { - return prevGroupTargets.stream() - .map(prevGroupId -> resolveNewGroupId(prevComponent, currComponent, prevGroupId)) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(toList()); + return prevGroupTargets.stream().map(prevGroupId -> resolveNewGroupId(prevComponent, currComponent, prevGroupId)).filter(Optional::isPresent) + .map(Optional::get).collect(toList()); } private Optional resolveNewInstId(Component prevCmpt, Component newCmpt, String prevInstanceId) { - return prevCmpt.getComponentInstanceById(prevInstanceId) - .map(ComponentInstance::getName) - .flatMap(newCmpt::getComponentInstanceByName) - .map(ComponentInstance::getUniqueId); + return prevCmpt.getComponentInstanceById(prevInstanceId).map(ComponentInstance::getName).flatMap(newCmpt::getComponentInstanceByName) + .map(ComponentInstance::getUniqueId); } private Optional resolveNewGroupId(Component prevCmpt, Component newCmpt, String prevGroupId) { - return prevCmpt.getGroupById(prevGroupId) - .map(GroupDefinition::getInvariantName) - .flatMap(newCmpt::getGroupByInvariantName) - .map(GroupDefinition::getUniqueId); + return prevCmpt.getGroupById(prevGroupId).map(GroupDefinition::getInvariantName).flatMap(newCmpt::getGroupByInvariantName) + .map(GroupDefinition::getUniqueId); } - } 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 431daff253..6f1a1e1ca8 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 @@ -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. @@ -17,21 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.property; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.model.InputDefinition; -import org.springframework.stereotype.Component; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.be.components.merge.property.PropertyInstanceMergeDataBuilder.buildDataForMerging; import java.util.Collections; import java.util.List; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.openecomp.sdc.be.components.merge.property.PropertyInstanceMergeDataBuilder.buildDataForMerging; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +import org.springframework.stereotype.Component; @Component -public class DataDefinitionsValuesMergingBusinessLogic { +public class DataDefinitionsValuesMergingBusinessLogic { private PropertyDataValueMergeBusinessLogic propertyValueMergeBL; @@ -40,24 +38,28 @@ public class DataDefinitionsValuesMergingBusinessLogic { } /** - * Merge previous version data definition values into the new version data definition. - * A data definition value is merged if it had a value in previous version and has no value in the current version. - * in case a property get input value has no corresponding input in the current version its value will not be merged - * @param oldInstanceDataDefinition the currently persisted instance data definitions - * @param oldInputs the previous version inputs + * Merge previous version data definition values into the new version data definition. A data definition value is merged if it had a value in + * previous version and has no value in the current version. in case a property get input value has no corresponding input in the current version + * its value will not be merged + * + * @param oldInstanceDataDefinition the currently persisted instance data definitions + * @param oldInputs the previous version inputs * @param updatedInstanceDataDefinition the currently being update instance data definitions - * @param newInputs the new version inputs + * @param newInputs the new version inputs */ - public void mergeInstanceDataDefinitions(List oldInstanceDataDefinition, List oldInputs, List updatedInstanceDataDefinition, List newInputs) { + public void mergeInstanceDataDefinitions(List oldInstanceDataDefinition, List oldInputs, + List updatedInstanceDataDefinition, + List newInputs) { if (isEmpty(updatedInstanceDataDefinition) || isEmpty(oldInstanceDataDefinition)) { return; } - List mergePropertyData = buildDataForMerging(oldInstanceDataDefinition, oldInputs, updatedInstanceDataDefinition, newInputs); + List mergePropertyData = buildDataForMerging(oldInstanceDataDefinition, oldInputs, updatedInstanceDataDefinition, + newInputs); mergePropertyData.forEach(this::mergeInstanceDefinition); - } - public void mergeInstanceDataDefinitions(List oldInstanceDataDefinition, List updatedInstanceDataDefinition) { + public void mergeInstanceDataDefinitions(List oldInstanceDataDefinition, + List updatedInstanceDataDefinition) { List emptyInputsList = Collections.emptyList(); mergeInstanceDataDefinitions(oldInstanceDataDefinition, emptyInputsList, updatedInstanceDataDefinition, emptyInputsList); } @@ -71,5 +73,4 @@ public class DataDefinitionsValuesMergingBusinessLogic { private boolean isSameType(PropertyDataDefinition oldDataDefinition, PropertyDataDefinition updatedDataDefinition) { return oldDataDefinition.typeEquals(updatedDataDefinition); } - } 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 3239608007..32d1443ef1 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 @@ -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. @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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. - * + * 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. */ public class MergePropertyData { @@ -36,7 +33,6 @@ public class MergePropertyData { private PropertyDataDefinition oldProp; /*The new state of the instance property to merge */ private PropertyDataDefinition newProp; - private List getInputNamesToMerge = new ArrayList<>(); public PropertyDataDefinition getOldProp() { @@ -48,15 +44,15 @@ public class MergePropertyData { return this; } + public PropertyDataDefinition getNewProp() { + return newProp; + } + public MergePropertyData setNewProp(PropertyDataDefinition newProp) { this.newProp = newProp; return this; } - public PropertyDataDefinition getNewProp() { - return newProp; - } - public void addAddGetInputNamesToMerge(List getInputsNameToMerge) { getInputNamesToMerge.addAll(getInputsNameToMerge); } @@ -68,5 +64,4 @@ public class MergePropertyData { public boolean isGetInputProp() { return oldProp.isGetInputProperty(); } - } 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 0c6a6aee4a..9888129071 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 @@ -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. @@ -17,50 +17,45 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.property; import com.google.gson.Gson; import fj.data.Either; +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 org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.be.tosca.PropertyConvertor; import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -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 public class PropertyDataValueMergeBusinessLogic { private static final Logger LOGGER = Logger.getLogger(PropertyDataValueMergeBusinessLogic.class); - private final PropertyValueMerger propertyValueMerger; private final ApplicationDataTypeCache dataTypeCache; - private final PropertyConvertor propertyConvertor; private final Gson gson = new Gson(); @Autowired - public PropertyDataValueMergeBusinessLogic(PropertyValueMerger propertyValueMerger, - ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) { + public PropertyDataValueMergeBusinessLogic(PropertyValueMerger propertyValueMerger, ApplicationDataTypeCache dataTypeCache, + PropertyConvertor propertyConvertor) { this.propertyValueMerger = propertyValueMerger; this.dataTypeCache = dataTypeCache; this.propertyConvertor = propertyConvertor; } /** - * * @param oldProp the old property to merge value from * @param newProp the new property to merge value into */ @@ -68,33 +63,32 @@ public class PropertyDataValueMergeBusinessLogic { Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { LOGGER.debug("failed to fetch data types, skip merging of previous property values. status: {}", dataTypesEither.right().value()); - } - else { + } else { mergePropertyValue(oldProp, newProp, dataTypesEither.left().value(), getInputNamesToMerge); } } - - private void mergePropertyValue(PropertyDataDefinition oldProp, PropertyDataDefinition newProp, Map dataTypes, List getInputNamesToMerge) { + + private void mergePropertyValue(PropertyDataDefinition oldProp, PropertyDataDefinition newProp, Map dataTypes, + List getInputNamesToMerge) { Object oldValAsObject = convertPropertyStrValueToObject(oldProp, dataTypes); Object newValAsObject = convertPropertyStrValueToObject(newProp, dataTypes); - if(oldValAsObject != null){ - Object mergedValue = propertyValueMerger.merge(oldValAsObject, newValAsObject, getInputNamesToMerge, newProp.getType(), newProp.getSchemaType(), dataTypes); + if (oldValAsObject != null) { + Object mergedValue = propertyValueMerger + .merge(oldValAsObject, newValAsObject, getInputNamesToMerge, newProp.getType(), newProp.getSchemaType(), dataTypes); newProp.setValue(convertPropertyValueObjectToString(mergedValue)); - mergePropertyGetInputsValues(oldProp, newProp); } - } - + private String convertPropertyValueObjectToString(Object mergedValue) { if (PropertyValueMerger.isEmptyValue(mergedValue)) { return null; } - return mergedValue instanceof String? mergedValue.toString() : gson.toJson(mergedValue); + return mergedValue instanceof String ? mergedValue.toString() : gson.toJson(mergedValue); } private Object convertPropertyStrValueToObject(PropertyDataDefinition propertyDataDefinition, Map dataTypes) { - String propValue = propertyDataDefinition.getValue() == null ? "": propertyDataDefinition.getValue(); + String propValue = propertyDataDefinition.getValue() == null ? "" : propertyDataDefinition.getValue(); String propertyType = propertyDataDefinition.getType(); String innerType = propertyDataDefinition.getSchemaType(); return propertyConvertor.convertToToscaObject(propertyDataDefinition, propValue, dataTypes, true); @@ -114,10 +108,8 @@ public class PropertyDataValueMergeBusinessLogic { List oldGetInputValues = oldProp.getGetInputValues(); List newGetInputValues = Optional.ofNullable(newProp.getGetInputValues()).orElse(Collections.emptyList()); List newGetInputNames = newGetInputValues.stream().map(GetInputValueDataDefinition::getInputName).collect(Collectors.toList()); - return oldGetInputValues.stream() - .filter(getInput -> !newGetInputNames.contains(getInput.getInputName())) - .filter(getInput -> isValueContainsGetInput(getInput.getInputName(), newProp.getValue())) - .collect(Collectors.toList()); + return oldGetInputValues.stream().filter(getInput -> !newGetInputNames.contains(getInput.getInputName())) + .filter(getInput -> isValueContainsGetInput(getInput.getInputName(), newProp.getValue())).collect(Collectors.toList()); } private boolean isValueContainsGetInput(String inputName, String value) { 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 d67f46fb07..79e04031f6 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 @@ -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. @@ -17,39 +17,36 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.property; -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.Objects; 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; class PropertyInstanceMergeDataBuilder { private PropertyInstanceMergeDataBuilder() { } - static List buildDataForMerging(List oldProps, - List oldInputs, - List newProps, - List newInputs) { - + static List buildDataForMerging(List oldProps, List oldInputs, + List newProps, List newInputs) { Map oldPropsByName = MapUtil.toMap(oldProps, T::getName); Map oldInputsByName = MapUtil.toMap(oldInputs, InputDefinition::getName); Map newPropsByName = MapUtil.toMap(newProps, T::getName); Map newInputsByName = MapUtil.toMap(newInputs, InputDefinition::getName); return buildMergeData(oldPropsByName, oldInputsByName, newPropsByName, newInputsByName); - } - private static List buildMergeData(Map oldPropsByName, Map oldInputsByName, Map newPropsByName, Map newInputsByName) { + private static List buildMergeData(Map oldPropsByName, + Map oldInputsByName, + Map newPropsByName, + Map newInputsByName) { List mergeData = new ArrayList<>(); newPropsByName.forEach((name, prop) -> { if (oldPropsByName.containsKey(name)) { @@ -59,36 +56,34 @@ class PropertyInstanceMergeDataBuilder { return mergeData; } - private static MergePropertyData buildMergePropertyData(PropertyDataDefinition oldProp, - Map oldInputsByName, - PropertyDataDefinition newProp, - Map newInputsByName) { + private static MergePropertyData buildMergePropertyData(PropertyDataDefinition oldProp, Map oldInputsByName, + PropertyDataDefinition newProp, Map newInputsByName) { MergePropertyData mergePropertyData = new MergePropertyData(); - mergePropertyData.setOldProp(oldProp) - .setNewProp(newProp); + mergePropertyData.setOldProp(oldProp).setNewProp(newProp); if (oldProp.isGetInputProperty()) { setGetInputData(oldProp, oldInputsByName, newInputsByName, mergePropertyData); - } return mergePropertyData; } - private static void setGetInputData(PropertyDataDefinition oldProp, Map oldInputsByName, Map newInputsByName, MergePropertyData mergePropertyData) { + private static void setGetInputData(PropertyDataDefinition oldProp, Map oldInputsByName, + Map newInputsByName, MergePropertyData mergePropertyData) { List oldDeclaredByUserInputNames = getOldDeclaredInputsByUser(oldProp.getGetInputValues(), oldInputsByName); List oldGetInputNamesWhichExistInNewVersion = getOldGetInputNamesWhichExistInNewVersion(oldProp.getGetInputValues(), newInputsByName); mergePropertyData.addAddGetInputNamesToMerge(oldDeclaredByUserInputNames); mergePropertyData.addAddGetInputNamesToMerge(oldGetInputNamesWhichExistInNewVersion); } - private static List getOldGetInputNamesWhichExistInNewVersion(List getInputValues, Map newInputsByName) { - return getInputValues.stream().map(GetInputValueDataDefinition::getInputName).filter(newInputsByName::containsKey).collect(Collectors.toList()); + private static List getOldGetInputNamesWhichExistInNewVersion(List getInputValues, + Map newInputsByName) { + return getInputValues.stream().map(GetInputValueDataDefinition::getInputName).filter(newInputsByName::containsKey) + .collect(Collectors.toList()); } - private static List getOldDeclaredInputsByUser(List getInputValues, Map oldInputsByName) { - return getInputValues.stream().map(GetInputValueDataDefinition::getInputName) - .map(oldInputsByName::get) - .filter(oldInput -> Objects.nonNull(oldInput) && oldInput.getInstanceUniqueId() != null) - .map(PropertyDataDefinition::getName) - .collect(Collectors.toList()); + private static List getOldDeclaredInputsByUser(List getInputValues, + Map oldInputsByName) { + return getInputValues.stream().map(GetInputValueDataDefinition::getInputName).map(oldInputsByName::get) + .filter(oldInput -> Objects.nonNull(oldInput) && oldInput.getInstanceUniqueId() != null).map(PropertyDataDefinition::getName) + .collect(Collectors.toList()); } } 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 39aec8f80b..de6a4f9dbf 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 @@ -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. @@ -17,9 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.property; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.model.DataTypeDefinition; @@ -28,21 +32,21 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.utils.TypeUtils; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - @Component public class PropertyValueMerger { - + + static boolean isEmptyValue(Object val) { + return val == null || val instanceof String && StringUtils.isEmpty((String) val) || val instanceof Map && ((Map) val).isEmpty() + || val instanceof List && ((List) val).isEmpty(); + } + @SuppressWarnings("unchecked") /** * merges property value oldVal into property value newVal recursively * @param oldVal - cannot be {@code Null} */ - protected Object merge(Object oldVal, Object newVal, List inputNamesToMerge, String type, String innerType, Map dataTypes) { + protected Object merge(Object oldVal, Object newVal, List inputNamesToMerge, String type, String innerType, + Map dataTypes) { if (isEmptyValue(newVal)) { return removeUnwantedGetInputValues(oldVal, inputNamesToMerge); } @@ -57,26 +61,28 @@ public class PropertyValueMerger { } return newVal; } - - private Map mergeMapValue(Map oldValMap, Map newValMap, List inputNamesToMerge, String type, String innertType, Map dataTypes) { + + private Map mergeMapValue(Map oldValMap, Map newValMap, List inputNamesToMerge, + String type, String innertType, Map dataTypes) { mergeEntriesExistInOldValue(oldValMap, newValMap, inputNamesToMerge, type, innertType, dataTypes);//continue the recursion if (type != null && !type.equals("map") && !type.equals("json")) { setOldEntriesNotExistInNewValue(oldValMap, newValMap, inputNamesToMerge); } - return newValMap; } - private void mergeEntriesExistInOldValue(Map oldValMap, Map newValMap, List inputNamesToMerge, String type, String innerType, Map dataTypes) { + private void mergeEntriesExistInOldValue(Map oldValMap, Map newValMap, List inputNamesToMerge, + String type, String innerType, Map dataTypes) { for (Map.Entry newValEntry : newValMap.entrySet()) { Object oldVal = oldValMap.get(newValEntry.getKey()); if (oldVal != null) { ImmutablePair types = getTypeAndInnerTypePair(newValEntry.getKey(), type, innerType, dataTypes); - newValMap.put(newValEntry.getKey(), merge(oldVal, newValEntry.getValue(), inputNamesToMerge, types.getLeft(), types.getRight(), dataTypes)); + newValMap.put(newValEntry.getKey(), + merge(oldVal, newValEntry.getValue(), inputNamesToMerge, types.getLeft(), types.getRight(), dataTypes)); } } } - + private void setOldEntriesNotExistInNewValue(Map oldVal, Map newVal, List getInputNamesToMerge) { for (Map.Entry oldValEntry : oldVal.entrySet()) { if (!isInputEntry(oldValEntry) || isInputToMerge(getInputNamesToMerge, oldValEntry)) { @@ -85,48 +91,40 @@ public class PropertyValueMerger { } } } - - private ImmutablePair getTypeAndInnerTypePair(String propName, String type, String innerType, Map dataTypes) { + + private ImmutablePair getTypeAndInnerTypePair(String propName, String type, String innerType, + Map dataTypes) { if (type == null || (ToscaPropertyType.isScalarType(type) && ToscaPropertyType.isScalarType(innerType))) { return ImmutablePair.of(innerType, null); } - String newInnerType = null; DataTypeDefinition innerTypeDef = dataTypes.get(type); if (innerTypeDef != null) { List properties = innerTypeDef.getProperties(); - if (properties!= null) { + if (properties != null) { Optional optionalProperty = findProperty(properties, propName); - - innerType = optionalProperty.map(PropertyDefinition::getType) - .orElse(innerType); - - newInnerType = optionalProperty.map(PropertyDefinition::getSchemaType) - .orElse(null); + innerType = optionalProperty.map(PropertyDefinition::getType).orElse(innerType); + newInnerType = optionalProperty.map(PropertyDefinition::getSchemaType).orElse(null); } } - return ImmutablePair.of(innerType, newInnerType); } - + private Optional findProperty(List properties, String propName) { - return properties.stream() - .filter(p -> propName.equals(p.getName())) - .findFirst(); + return properties.stream().filter(p -> propName.equals(p.getName())).findFirst(); } - private List mergeListValue(List oldVal, List newVal, List inputNamesToMerge, String innerType, Map dataTypes) { + private List mergeListValue(List oldVal, List newVal, List inputNamesToMerge, String innerType, + Map dataTypes) { List mergedList = newVal; - if (oldVal.size() == newVal.size()) { mergedList = mergeLists(oldVal, newVal, inputNamesToMerge, innerType, dataTypes); } - return mergedList; } - - private List mergeLists(List oldVal, List newVal, List inputNamesToMerge, String innerType, Map dataTypes) { + private List mergeLists(List oldVal, List newVal, List inputNamesToMerge, String innerType, + Map dataTypes) { int minListSize = Math.min(oldVal.size(), newVal.size()); List mergedList = new ArrayList<>(); for (int i = 0; i < minListSize; i++) { @@ -135,27 +133,18 @@ public class PropertyValueMerger { } return mergedList; } - - + private Object mergeScalarValue(Object oldVal, Object newVal) { return isEmptyValue(newVal) ? oldVal : newVal; } - - static boolean isEmptyValue(Object val) { - return val == null || - val instanceof String && StringUtils.isEmpty((String)val) || - val instanceof Map && ((Map) val).isEmpty() || - val instanceof List && ((List) val).isEmpty(); - } - @SuppressWarnings("unchecked") Object removeUnwantedGetInputValues(Object val, List inputNamesToMerge) { - if (val instanceof Map) { + if (val instanceof Map) { return removeUnwantedGetInputValues((Map) val, inputNamesToMerge); } if (val instanceof List) { - return removeUnwantedGetInputValues((List)val, inputNamesToMerge); + return removeUnwantedGetInputValues((List) val, inputNamesToMerge); } return val; } @@ -166,7 +155,7 @@ public class PropertyValueMerger { private Map removeUnwantedGetInputValues(Map val, List inputNamesToMerge) { return val.entrySet().stream().filter(entry -> !isInputEntry(entry) || isInputToMerge(inputNamesToMerge, entry)) - .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), inputNamesToMerge))); + .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), inputNamesToMerge))); } private boolean isInputToMerge(List inputNamesToMerge, Map.Entry entry) { @@ -186,12 +175,10 @@ public class PropertyValueMerger { } private String retrieveInputName(Object inputValue) { - return inputValue instanceof List ? (String)((List) inputValue).get(0) : (String)inputValue; + return inputValue instanceof List ? (String) ((List) inputValue).get(0) : (String) inputValue; } protected boolean isInputEntry(Map.Entry oldValEntry) { return oldValEntry.getKey().equals(TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeCommandsFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeCommandsFactory.java index ec25a9d742..31a09e9254 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeCommandsFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeCommandsFactory.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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.resource; import fj.data.Either; +import java.util.List; import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand; import org.openecomp.sdc.be.components.merge.ComponentsMergeCommand; import org.openecomp.sdc.be.components.merge.TopologyComparator; @@ -29,8 +29,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; import org.springframework.stereotype.Component; -import java.util.List; - @Component public class MergeCommandsFactory { @@ -38,16 +36,15 @@ public class MergeCommandsFactory { private final List mergeCommands; private final TopologyComparator topologyComparator; - public MergeCommandsFactory(List globalMergeCommands, List mergeCommands, TopologyComparator topologyComparator) { + public MergeCommandsFactory(List globalMergeCommands, List mergeCommands, + TopologyComparator topologyComparator) { this.globalMergeCommands = globalMergeCommands; this.mergeCommands = mergeCommands; this.topologyComparator = topologyComparator; } public Either, ActionStatus> getMergeCommands(Resource prevResource, Resource currResource) { - return topologyComparator.isTopologyChanged(prevResource, currResource) - .left() - .map(topologyChanged -> topologyChanged ? globalMergeCommands : mergeCommands); - + return topologyComparator.isTopologyChanged(prevResource, currResource).left() + .map(topologyChanged -> topologyChanged ? globalMergeCommands : mergeCommands); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.java index 7058a62a20..a24a4f3532 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.resource; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -26,5 +25,4 @@ import org.openecomp.sdc.be.model.Resource; public interface MergeResourceBusinessLogic { ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource); - } 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 98957e000d..d8d6841d15 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 @@ -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. @@ -17,26 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.resource; +import java.util.List; import org.openecomp.sdc.be.components.merge.ComponentsMergeCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import java.util.List; - @Component public class ResourceDataMergeBusinessLogic implements MergeResourceBusinessLogic { - private static final Logger log = Logger.getLogger(ResourceDataMergeBusinessLogic.class); public static final int FIRST_COMMAND = 0; public static final int PENULTIMATE_COMMAND = Integer.MAX_VALUE - 1; public static final int LAST_COMMAND = Integer.MAX_VALUE; public static final int ANY_ORDER_COMMAND = 1; - + private static final Logger log = Logger.getLogger(ResourceDataMergeBusinessLogic.class); private MergeCommandsFactory mergeCommandsFactory; public ResourceDataMergeBusinessLogic(MergeCommandsFactory mergeCommandsFactory) { @@ -49,19 +46,19 @@ public class ResourceDataMergeBusinessLogic implements MergeResourceBusinessLogi return ActionStatus.OK; } return mergeCommandsFactory.getMergeCommands(oldResource, newResource) - .either(mergeCommands -> executeMergeCommands(oldResource, newResource, mergeCommands), - err -> err); + .either(mergeCommands -> executeMergeCommands(oldResource, newResource, mergeCommands), err -> err); } - private ActionStatus executeMergeCommands(Resource oldResource, Resource newResource, List componentMergingCommands) { + private ActionStatus executeMergeCommands(Resource oldResource, Resource newResource, + List componentMergingCommands) { for (ComponentsMergeCommand componentMergeCommand : componentMergingCommands) { ActionStatus mergeStatus = componentMergeCommand.mergeComponents(oldResource, newResource); if (mergeStatus != ActionStatus.OK) { - log.debug("failed on merge command {} of resource {} status is {}", componentMergeCommand.description(), newResource.getUniqueId(), mergeStatus); + log.debug("failed on merge command {} of resource {} status is {}", componentMergeCommand.description(), newResource.getUniqueId(), + mergeStatus); return mergeStatus; } } return ActionStatus.OK; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/CapabilityOwner.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/CapabilityOwner.java index 61d3ba862d..f304090968 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/CapabilityOwner.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/CapabilityOwner.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. @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.utils; -import org.openecomp.sdc.be.model.CapabilityDefinition; +import static java.util.Collections.emptyMap; import java.util.List; import java.util.Map; - -import static java.util.Collections.emptyMap; +import org.openecomp.sdc.be.model.CapabilityDefinition; public class CapabilityOwner { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/ComponentInstanceBuildingBlocks.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/ComponentInstanceBuildingBlocks.java index 549a14d5eb..5f9fbf4b5b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/ComponentInstanceBuildingBlocks.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/ComponentInstanceBuildingBlocks.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. @@ -17,12 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.utils; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.GroupDefinition; +import static org.openecomp.sdc.be.dao.utils.MapUtil.mergeMaps; +import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap; import java.util.ArrayList; import java.util.HashMap; @@ -30,23 +28,24 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; - -import static org.openecomp.sdc.be.dao.utils.MapUtil.mergeMaps; -import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; public class ComponentInstanceBuildingBlocks { private Map groups = new HashMap<>(); private Map vfcInstances = new HashMap<>(); - private ComponentInstanceBuildingBlocks(){} + private ComponentInstanceBuildingBlocks() { + } private ComponentInstanceBuildingBlocks(List groups, List vfcInstances) { this.groups = groups == null ? new HashMap<>() : toMap(groups, GroupDataDefinition::getUniqueId); this.vfcInstances = vfcInstances == null ? new HashMap<>() : toMap(vfcInstances, ComponentInstance::getUniqueId); } - private ComponentInstanceBuildingBlocks(Map groups, Map vfcInstances) { + private ComponentInstanceBuildingBlocks(Map groups, Map vfcInstances) { this.groups = groups == null ? new HashMap<>() : groups; this.vfcInstances = vfcInstances == null ? new HashMap<>() : vfcInstances; } @@ -59,11 +58,9 @@ public class ComponentInstanceBuildingBlocks { return new ComponentInstanceBuildingBlocks(); } - @SuppressWarnings("unchecked") static ComponentInstanceBuildingBlocks merge(ComponentInstanceBuildingBlocks first, ComponentInstanceBuildingBlocks second) { - return new ComponentInstanceBuildingBlocks(mergeMaps(first.groups, second.groups), - mergeMaps(first.vfcInstances, second.vfcInstances)); + return new ComponentInstanceBuildingBlocks(mergeMaps(first.groups, second.groups), mergeMaps(first.vfcInstances, second.vfcInstances)); } public List getGroups() { @@ -76,12 +73,9 @@ public class ComponentInstanceBuildingBlocks { public List getCapabilitiesOwners() { Stream groupsStream = groups.values().stream() - .map(grp -> new CapabilityOwner(grp.getUniqueId(), grp.getInvariantName(), grp.getCapabilities())); - + .map(grp -> new CapabilityOwner(grp.getUniqueId(), grp.getInvariantName(), grp.getCapabilities())); Stream instanceStream = vfcInstances.values().stream() - .map(instance -> new CapabilityOwner(instance.getUniqueId(), instance.getName(), instance.getCapabilities())); - + .map(instance -> new CapabilityOwner(instance.getUniqueId(), instance.getName(), instance.getCapabilities())); return Stream.concat(groupsStream, instanceStream).collect(Collectors.toList()); } - } 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 index 00a2f6827f..e347df916e 100644 --- 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 @@ -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. @@ -17,10 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.merge.utils; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; +import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap; + import fj.data.Either; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; @@ -39,29 +51,15 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import static java.util.Collections.emptyMap; -import static java.util.Collections.singletonList; -import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap; - /** * This class is Utils class but it should be bean - * @author dr2032 * + * @author dr2032 */ @org.springframework.stereotype.Component public class MergeInstanceUtils { + private static final Logger log = Logger.getLogger(MergeInstanceUtils.class); - private final ToscaOperationFacade toscaOperationFacade; private final ExceptionUtils exceptionUtils; @@ -70,27 +68,31 @@ public class MergeInstanceUtils { this.exceptionUtils = exceptionUtils; } + 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; + } + /** - * @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 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 the old capabilities owner ids * @return a map of capability owner IDs of old component instance to capability owner IDs of the new component instance */ - public Map mapOldToNewCapabilitiesOwnerIds(Component container, - Component origInstanceNode, - String newInstanceId, + public Map mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String newInstanceId, List oldCapabilitiesOwnerIds) { - Map resultMap; - if (ModelConverter.isAtomicComponent(origInstanceNode) || isCVFC(origInstanceNode)) { resultMap = prepareMapForAtomicComponent(newInstanceId, oldCapabilitiesOwnerIds); - } - else { + } else { resultMap = prepareMapForNonAtomicComponent(container, origInstanceNode, newInstanceId, oldCapabilitiesOwnerIds); } - return resultMap; } @@ -100,8 +102,8 @@ public class MergeInstanceUtils { * @return a map between capability owner IDs of old component instance to capability owner IDs of the new component instance */ public Map mapOldToNewCapabilitiesOwnerIds(ComponentInstance oldInstance, ComponentInstance newInstance) { - List prevCapabilityOwners = getInstanceAtomicBuildingBlocks(oldInstance).getCapabilitiesOwners(); - List newCapOwners = getInstanceAtomicBuildingBlocks(newInstance).getCapabilitiesOwners(); + List prevCapabilityOwners = getInstanceAtomicBuildingBlocks(oldInstance).getCapabilitiesOwners(); + List newCapOwners = getInstanceAtomicBuildingBlocks(newInstance).getCapabilitiesOwners(); return getCapabilitiesOwnerMapping(prevCapabilityOwners, newCapOwners); } @@ -113,15 +115,11 @@ public class MergeInstanceUtils { public List getUpdatedUiRelations(Component oldResource, Component newResource) { Map mapOldComponentInstances = buildComponentInstanceMap(oldResource, ComponentInstance::getUniqueId); Map mapNewComponentInstances = buildComponentInstanceMap(newResource, ComponentInstance::getName); - - return getUpdatedCapReqDefs(oldResource, newResource, - mapOldComponentInstances, - mapNewComponentInstances, - RequirementCapabilityRelDef::isOriginUI); + return getUpdatedCapReqDefs(oldResource, newResource, mapOldComponentInstances, mapNewComponentInstances, + RequirementCapabilityRelDef::isOriginUI); } /** - * * @param componentInstance the instance which its building blocks are to be returned * @return the atomic building (groups and instances) blocks which the given component instance is a composition of */ @@ -135,9 +133,8 @@ public class MergeInstanceUtils { } /** - * * @param componentInstance the instance which its building blocks are to be returned - * @param component the type thar the given component instance was created from + * @param component the type thar the given component instance was created from * @return the atomic building blocks (groups and instances) which the given component instance is a composition of */ public ComponentInstanceBuildingBlocks getInstanceAtomicBuildingBlocks(ComponentInstance componentInstance, Component component) { @@ -149,20 +146,19 @@ public class MergeInstanceUtils { if (componentInstance.getIsProxy()) { // Component is proxy and it doesn't contain required data instanceBuildingBlocks = getInstanceAtomicBuildingBlocks(componentInstance); - } - else { + } else { instanceBuildingBlocks = ComponentInstanceBuildingBlocks.of(new ArrayList<>(), singletonList(componentInstance)); } return instanceBuildingBlocks; - } - else { + } else { instanceBuildingBlocks = recursiveScanForAtomicBuildingBlocks(component); - if(org.apache.commons.collections.MapUtils.isNotEmpty(component.getCapabilities()) || org.apache.commons.collections.MapUtils.isNotEmpty(component.getRequirements())) { - ComponentInstanceBuildingBlocks nonAtomicBlocks = ComponentInstanceBuildingBlocks.of(new ArrayList<>(), singletonList(componentInstance)); + if (org.apache.commons.collections.MapUtils.isNotEmpty(component.getCapabilities()) || org.apache.commons.collections.MapUtils + .isNotEmpty(component.getRequirements())) { + ComponentInstanceBuildingBlocks nonAtomicBlocks = ComponentInstanceBuildingBlocks + .of(new ArrayList<>(), singletonList(componentInstance)); return ComponentInstanceBuildingBlocks.merge(instanceBuildingBlocks, nonAtomicBlocks); } return instanceBuildingBlocks; - } } @@ -176,13 +172,9 @@ public class MergeInstanceUtils { return createRequirementRelationMergeInfo(vfcInstances, ownerId, relDef); } - - public RequirementCapabilityRelDef restoreCapabilityRelation(RelationMergeInfo oldCapInfo, - String newInstanceId, - Map capOwnerByName, - Component updatedContainerComponent) { + public RequirementCapabilityRelDef restoreCapabilityRelation(RelationMergeInfo oldCapInfo, String newInstanceId, + Map capOwnerByName, Component updatedContainerComponent) { String oldCapOwnerName = oldCapInfo.getCapOwnerName(); - CapabilityOwner newCapOwner = capOwnerByName.get(oldCapOwnerName); if (newCapOwner != null) { // Append relation to updated container @@ -203,41 +195,30 @@ public class MergeInstanceUtils { } } - - - public RequirementCapabilityRelDef restoreRequirementRelation(RelationMergeInfo oldReqInfo, - String newInstanceId, - Map vfciMap, - Component updatedContainerComponent) { + public RequirementCapabilityRelDef restoreRequirementRelation(RelationMergeInfo oldReqInfo, String newInstanceId, + Map vfciMap, Component updatedContainerComponent) { String oldVfcInstanceName = oldReqInfo.getCapOwnerName(); - ComponentInstance newVfcInstance = vfciMap.get(oldReqInfo.getCapOwnerName()); 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()); + if (eitherComponent.isLeft()) { + String requirementUid = retrieveRequirementUid(oldReqInfo.getCapReqName(), eitherComponent.left().value()); oldRelationshipInfo.setRequirementUid(requirementUid); - } - else { + } else { log.debug("#restoreRequirementCapabilityRelDef - Unexpected error: resource was not loaded for VF ID: {}", vfcUid); } - if (updatedContainerComponent != null) { updatedContainerComponent.getComponentInstancesRelations().add(oldRelDef); } return oldRelDef; - } - else { + } else { log.debug("#restoreRequirementCapabilityRelDef - Skip relation since it was not found VFC Instance with name {}", oldVfcInstanceName); return null; } @@ -249,254 +230,204 @@ public class MergeInstanceUtils { private Map getCapabilitiesOwnerMapping(List oldCapOwners, List newCapOwners) { Map newCapOwnerNameMap = toMap(newCapOwners, CapabilityOwner::getName, (p1, p2) -> p1); - return oldCapOwners.stream() - .filter(oldCapOwner -> newCapOwnerNameMap.containsKey(oldCapOwner.getName())) - .collect(Collectors.toMap(CapabilityOwner::getUniqueId, oldCapOwner -> newCapOwnerNameMap.get(oldCapOwner.getName()).getUniqueId(), (p1, p2) -> p1)); - } - - 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; + return oldCapOwners.stream().filter(oldCapOwner -> newCapOwnerNameMap.containsKey(oldCapOwner.getName())).collect(Collectors + .toMap(CapabilityOwner::getUniqueId, oldCapOwner -> newCapOwnerNameMap.get(oldCapOwner.getName()).getUniqueId(), (p1, p2) -> p1)); } - private RequirementCapabilityRelDef mergeCapRelDefs(RequirementCapabilityRelDef capRelDefFrom, RequirementCapabilityRelDef capRelDefTo) { if (capRelDefFrom == capRelDefTo) { return capRelDefFrom; - } - else if (capRelDefFrom == null) { + } else if (capRelDefFrom == null) { return capRelDefTo; - } - else if (capRelDefTo == null) { + } else if (capRelDefTo == null) { return capRelDefFrom; } - RelationshipInfo relationshipInfoFrom = capRelDefFrom.resolveSingleRelationship().getRelation(); RelationshipInfo relationshipInfoTo = capRelDefTo.resolveSingleRelationship().getRelation(); - relationshipInfoFrom.setCapabilityOwnerId(relationshipInfoTo.getCapabilityOwnerId()); relationshipInfoFrom.setCapabilityUid(relationshipInfoTo.getCapabilityUid()); - return capRelDefFrom; } - - private Map buildComponentInstanceMap(Component oldRresource, Function getKeyFunc) { - return oldRresource.getComponentInstances().stream() - .collect(Collectors.toMap(getKeyFunc, Function.identity(), (p1, p2) -> p1)); + return oldRresource.getComponentInstances().stream().collect(Collectors.toMap(getKeyFunc, Function.identity(), (p1, p2) -> p1)); } private List getUpdatedCapReqDefs(Component oldResource, Component newComponent, Map mapOldComponentInstances, Map mapNewComponentInstances, Predicate filter) { - return oldResource.getComponentInstancesRelations().stream() - .filter(filter) - .map(rel -> createRelationMergeInfoPair(rel, mapOldComponentInstances)) - .map(infoPair -> restoreRequirementCapabilityRelDef(infoPair, mapNewComponentInstances)) - .filter(Objects::nonNull) - .filter(r-> capReqMatchExist(r, newComponent)) - .collect(Collectors.toList()); + return oldResource.getComponentInstancesRelations().stream().filter(filter) + .map(rel -> createRelationMergeInfoPair(rel, mapOldComponentInstances)) + .map(infoPair -> restoreRequirementCapabilityRelDef(infoPair, mapNewComponentInstances)).filter(Objects::nonNull) + .filter(r -> capReqMatchExist(r, newComponent)).collect(Collectors.toList()); } - private boolean capReqMatchExist(RequirementCapabilityRelDef rel, Component currentComponent) { - return currentComponent.getComponentInstances().stream() - .anyMatch(i->isFromInstance(i, rel)) && - currentComponent.getComponentInstances().stream() - .anyMatch(i->isToInstance(i, rel)); + return currentComponent.getComponentInstances().stream().anyMatch(i -> isFromInstance(i, rel)) && currentComponent.getComponentInstances() + .stream().anyMatch(i -> isToInstance(i, rel)); } private boolean isToInstance(ComponentInstance inst, RequirementCapabilityRelDef rel) { - return inst.getUniqueId().equals(rel.getToNode()) && - inst.getCapabilities().values() - .stream() - .flatMap(Collection::stream) - .anyMatch(cap->cap.getName().equals(rel.resolveSingleRelationship().getRelation().getCapability()) - && cap.getOwnerId().equals(rel.resolveSingleRelationship().getRelation().getCapabilityOwnerId())); + return inst.getUniqueId().equals(rel.getToNode()) && inst.getCapabilities().values().stream().flatMap(Collection::stream).anyMatch( + cap -> cap.getName().equals(rel.resolveSingleRelationship().getRelation().getCapability()) && cap.getOwnerId() + .equals(rel.resolveSingleRelationship().getRelation().getCapabilityOwnerId())); } private boolean isFromInstance(ComponentInstance inst, RequirementCapabilityRelDef rel) { - return inst.getUniqueId().equals(rel.getFromNode()) && - inst.getRequirements().values() - .stream() - .flatMap(Collection::stream) - .anyMatch(req->req.getName().equals(rel.resolveSingleRelationship().getRelation().getRequirement()) - && req.getOwnerId().equals(rel.resolveSingleRelationship().getRelation().getRequirementOwnerId())); + return inst.getUniqueId().equals(rel.getFromNode()) && inst.getRequirements().values().stream().flatMap(Collection::stream).anyMatch( + req -> req.getName().equals(rel.resolveSingleRelationship().getRelation().getRequirement()) && req.getOwnerId() + .equals(rel.resolveSingleRelationship().getRelation().getRequirementOwnerId())); } private ImmutablePair createRelationMergeInfoPair(RequirementCapabilityRelDef reqCapDef, Map mapOldComponentInstances) { - ComponentInstance oldComponentInstanceFrom = mapOldComponentInstances.get(reqCapDef.getFromNode()); RelationMergeInfo fromRelationMergeInfo = createRequirmentRelationMergeInfo(oldComponentInstanceFrom, reqCapDef); - ComponentInstance oldComponentInstanceTo = mapOldComponentInstances.get(reqCapDef.getToNode()); RelationMergeInfo toRelationMergeInfo = createCapabilityRelationMergeInfo(oldComponentInstanceTo, reqCapDef); return new ImmutablePair<>(fromRelationMergeInfo, toRelationMergeInfo); } - private RelationMergeInfo createRequirmentRelationMergeInfo(ComponentInstance componentInstance, RequirementCapabilityRelDef reqCapDef ) { - + private RelationMergeInfo createRequirmentRelationMergeInfo(ComponentInstance componentInstance, RequirementCapabilityRelDef reqCapDef) { List vfcInstances = getVfcInstances(componentInstance); - if (vfcInstances != null) { + if (vfcInstances != null) { return mapRelationRequirement(reqCapDef, vfcInstances); - } - else { + } else { log.debug("#createRelationMergeInfo - It's unexpected that vfc instnaces were not found for {}", componentInstance); return null; } } - private RelationMergeInfo createCapabilityRelationMergeInfo(ComponentInstance componentInstance, - RequirementCapabilityRelDef reqCapDef) { + private RelationMergeInfo createCapabilityRelationMergeInfo(ComponentInstance componentInstance, RequirementCapabilityRelDef reqCapDef) { List capabilityOwners = getInstanceAtomicBuildingBlocks(componentInstance).getCapabilitiesOwners(); return mapRelationCapability(reqCapDef, capabilityOwners); } - - private RequirementCapabilityRelDef restoreRequirementCapabilityRelDef(ImmutablePair mergeInfoPair, Map mapNewComponentInstances) { + private RequirementCapabilityRelDef restoreRequirementCapabilityRelDef(ImmutablePair mergeInfoPair, + Map mapNewComponentInstances) { RequirementCapabilityRelDef capRelDefFrom = restoreRequirementRelDef(mergeInfoPair, mapNewComponentInstances); RequirementCapabilityRelDef capRelDefTo = restoreCapabilityRelDef(mergeInfoPair, mapNewComponentInstances); - return mergeCapRelDefs(capRelDefFrom, capRelDefTo); } - private RequirementCapabilityRelDef restoreRequirementRelDef(ImmutablePair mergeInfoPair, Map mapNewComponentInstances) { + private RequirementCapabilityRelDef restoreRequirementRelDef(ImmutablePair mergeInfoPair, + Map mapNewComponentInstances) { RequirementCapabilityRelDef capRelDefFrom = null; RelationMergeInfo mergeInfoFrom = mergeInfoPair.getLeft(); if (mergeInfoFrom != null) { ComponentInstance newComponentInstanceFrom = mapNewComponentInstances.get(mergeInfoFrom.getCapOwnerName()); - if(newComponentInstanceFrom != null){ - capRelDefFrom = restoreRequirementRelDef(newComponentInstanceFrom, mergeInfoFrom, newComponentInstanceFrom.getUniqueId()); + if (newComponentInstanceFrom != null) { + capRelDefFrom = restoreRequirementRelDef(newComponentInstanceFrom, mergeInfoFrom, newComponentInstanceFrom.getUniqueId()); } - } - else { + } else { capRelDefFrom = null; } return capRelDefFrom; } - private RequirementCapabilityRelDef restoreCapabilityRelDef(ImmutablePair mergeInfoPair, Map mapNewComponentInstances) { + private RequirementCapabilityRelDef restoreCapabilityRelDef(ImmutablePair mergeInfoPair, + Map mapNewComponentInstances) { RequirementCapabilityRelDef capRelDefTo; RelationMergeInfo mergeInfoTo = mergeInfoPair.getRight(); if (mergeInfoTo != null) { ComponentInstance newComponentInstanceTo = mapNewComponentInstances.get(mergeInfoTo.getCapOwnerName()); capRelDefTo = restoreCapabilityRelDef(newComponentInstanceTo, mergeInfoTo, newComponentInstanceTo.getUniqueId()); - } - else { + } else { capRelDefTo = null; } return capRelDefTo; } - private RequirementCapabilityRelDef restoreRequirementRelDef(ComponentInstance newComponentInstance, RelationMergeInfo mergeInfoFrom, String newComponentInstanceFromId) { + private RequirementCapabilityRelDef restoreRequirementRelDef(ComponentInstance newComponentInstance, RelationMergeInfo mergeInfoFrom, + String newComponentInstanceFromId) { if (newComponentInstance != null) { List vfcInstances = getVfcInstances(newComponentInstance); - if(vfcInstances != null) { + if (vfcInstances != null) { Map vfciMap = toMap(vfcInstances, ComponentInstance::getName, (p1, p2) -> p1); return restoreRequirementRelation(mergeInfoFrom, newComponentInstanceFromId, vfciMap, null); - } - else { + } else { log.debug("#restoreRequirementCapabilityRelDef - It was not found VFC instances for component instance {}", newComponentInstance); } } return null; } - private RequirementCapabilityRelDef restoreCapabilityRelDef(ComponentInstance newComponentInstance, RelationMergeInfo mergeInfoTo, String newComponentInstanceToId) { + private RequirementCapabilityRelDef restoreCapabilityRelDef(ComponentInstance newComponentInstance, RelationMergeInfo mergeInfoTo, + String newComponentInstanceToId) { if (newComponentInstance != null) { List capsOwners = getInstanceAtomicBuildingBlocks(newComponentInstance).getCapabilitiesOwners(); - if(capsOwners != null) { + if (capsOwners != null) { Map vfciMap = toMap(capsOwners, CapabilityOwner::getName, (p1, p2) -> p1); return restoreCapabilityRelation(mergeInfoTo, newComponentInstanceToId, vfciMap, null); - } - else { + } else { log.debug("#restoreRequirementCapabilityRelDef - It was not found VFC instances for component instance {}", newComponentInstance); } } return null; } - private ComponentInstanceBuildingBlocks recursiveScanForAtomicBuildingBlocks(Component component) { ComponentInstanceBuildingBlocks capsOwners = ComponentInstanceBuildingBlocks.of(component.getGroups(), null); List componentInstances = component.safeGetComponentInstances(); // Go recursively to collect atomic components only - ComponentInstanceBuildingBlocks propsOwnersRec = componentInstances.stream() - .map(this::getInstanceAtomicBuildingBlocks) - .reduce(ComponentInstanceBuildingBlocks::merge) - .orElse(ComponentInstanceBuildingBlocks.empty()); + ComponentInstanceBuildingBlocks propsOwnersRec = componentInstances.stream().map(this::getInstanceAtomicBuildingBlocks) + .reduce(ComponentInstanceBuildingBlocks::merge).orElse(ComponentInstanceBuildingBlocks.empty()); return ComponentInstanceBuildingBlocks.merge(capsOwners, propsOwnersRec); } - 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("#prepareMapForAtomicComponent - For atomic component the list of old capabilities owner Ids should contains one element while actual size is {},", oldCapabilityOwnerIdsSize); + } else { + log.debug( + "#prepareMapForAtomicComponent - For atomic component the list of old capabilities owner Ids should contains one element while actual size is {},", + oldCapabilityOwnerIdsSize); resultMap = emptyMap(); } - return resultMap; } - private Map prepareMapForNonAtomicComponent(Component container, Component origInstanceNode, - String newInstanceId, List oldCapabilitiesOwnerIds) { + private Map prepareMapForNonAtomicComponent(Component container, Component origInstanceNode, String newInstanceId, + List oldCapabilitiesOwnerIds) { ComponentInstance newInstance = container.getComponentInstanceById(newInstanceId).orElse(null); if (newInstance == null) { log.debug("#prepareMapForNonAtomicComponent - Failed to get component instance by newInstanceId: {}.", newInstanceId); return emptyMap(); } List prevCapOwners = recursiveScanForAtomicBuildingBlocks(origInstanceNode).getCapabilitiesOwners(); - Component origNewCmpt = toscaOperationFacade.getToscaElement(newInstance.getActualComponentUid()).left().on(err -> exceptionUtils.rollBackAndThrow(err, newInstance.getActualComponentUid())); + Component origNewCmpt = toscaOperationFacade.getToscaElement(newInstance.getActualComponentUid()).left() + .on(err -> exceptionUtils.rollBackAndThrow(err, newInstance.getActualComponentUid())); return mapOldOwnerIdsToNewOnes(oldCapabilitiesOwnerIds, prevCapOwners, newInstance, origNewCmpt); } - private Map mapOldOwnerIdsToNewOnes(List oldCapabilitiesOwnerIds, - List prevCapOwners, ComponentInstance newInstance, Component origNewInstanceType) { + private Map mapOldOwnerIdsToNewOnes(List oldCapabilitiesOwnerIds, List prevCapOwners, + ComponentInstance newInstance, Component origNewInstanceType) { List newCapOwners = getInstanceAtomicBuildingBlocks(newInstance, origNewInstanceType).getCapabilitiesOwners(); return getCapabilitiesOwnerMapping(oldCapabilitiesOwnerIds, prevCapOwners, newCapOwners); } - private Map getCapabilitiesOwnerMapping(List oldCapabilitiesOwnerIds, List prevCapOwners, List newCapOwners) { + private Map getCapabilitiesOwnerMapping(List oldCapabilitiesOwnerIds, List prevCapOwners, + List newCapOwners) { Map capOwnersByName = toMap(newCapOwners, CapabilityOwner::getName, (p1, p2) -> p1); - return prevCapOwners - .stream() - .filter(oldCapOwner -> oldCapabilitiesOwnerIds.contains(oldCapOwner.getUniqueId())) - .filter(oldCapOwner -> capOwnersByName.containsKey(oldCapOwner.getName())) - .collect(Collectors.toMap(CapabilityOwner::getUniqueId, oldCapOwner -> capOwnersByName.get(oldCapOwner.getName()).getUniqueId(), (p1, p2) -> p1)); + return prevCapOwners.stream().filter(oldCapOwner -> oldCapabilitiesOwnerIds.contains(oldCapOwner.getUniqueId())) + .filter(oldCapOwner -> capOwnersByName.containsKey(oldCapOwner.getName())).collect(Collectors + .toMap(CapabilityOwner::getUniqueId, oldCapOwner -> capOwnersByName.get(oldCapOwner.getName()).getUniqueId(), (p1, p2) -> p1)); } - - private RelationMergeInfo createCapabilityRelationMergeInfo(List vfcInstances, String ownerId, RequirementCapabilityRelDef relation) { - return vfcInstances.stream() - .filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId)) - .map(capabilityOwner -> getCapabilityMergeInfo(capabilityOwner, relation)) - .findAny() - .orElse(null); + private RelationMergeInfo createCapabilityRelationMergeInfo(List vfcInstances, String ownerId, + RequirementCapabilityRelDef relation) { + return vfcInstances.stream().filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId)) + .map(capabilityOwner -> getCapabilityMergeInfo(capabilityOwner, relation)).findAny().orElse(null); } - - private RelationMergeInfo createRequirementRelationMergeInfo(List vfcInstances, String ownerId, RequirementCapabilityRelDef relation) { - return vfcInstances.stream() - .filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId)) - .map(currVfcInst -> mapVfcInstanceRequirement(currVfcInst, relation)) - .filter(Objects::nonNull) - .findAny() - .orElse(null); + private RelationMergeInfo createRequirementRelationMergeInfo(List vfcInstances, String ownerId, + RequirementCapabilityRelDef relation) { + return vfcInstances.stream().filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId)) + .map(currVfcInst -> mapVfcInstanceRequirement(currVfcInst, relation)).filter(Objects::nonNull).findAny().orElse(null); } private RelationMergeInfo getCapabilityMergeInfo(CapabilityOwner capabilityOwner, RequirementCapabilityRelDef relDef) { @@ -509,80 +440,57 @@ public class MergeInstanceUtils { capabilityType = capabilityDef.getType(); capabilityName = capabilityDef.getName(); } else { - log.debug("#getCapabilityMergeInfo - Failed to retrieve capability type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getCapability(), capabilityUniqueId); + log.debug("#getCapabilityMergeInfo - 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, capOwnerName, relDef); } - + 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()) { + 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("#mapVfcInstanceRequirement - Failed to retrieve requirement type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getRequirement(), requirementUniqueId); + } else { + log.debug("#mapVfcInstanceRequirement - Failed to retrieve requirement type for relation with name: {} and uniqueId {}", + relDef.resolveSingleRelationship().getRelation().getRequirement(), requirementUniqueId); requirementType = null; - requirementName = null; + requirementName = null; } - return new RelationMergeInfo(requirementType, requirementName, vfcInstanceName, relDef); - } - else { - log.debug("#mapVfcInstanceRequirement - Failed to load VFC by uid {}", vfcUid); + } else { + log.debug("#mapVfcInstanceRequirement - Failed to load VFC by uid {}", vfcUid); return null; } } private CapabilityDefinition retrieveCapabilityDefinition(String uniqueId, CapabilityOwner capabilityOwner) { - return capabilityOwner.getCapabilities().values().stream() - .flatMap(List::stream) - .filter(Objects::nonNull) - .filter(def -> uniqueId.equals(def.getUniqueId())) - .findFirst() - .orElse(null); - } - + return capabilityOwner.getCapabilities().values().stream().flatMap(List::stream).filter(Objects::nonNull) + .filter(def -> uniqueId.equals(def.getUniqueId())).findFirst().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); - } - + return vfc.getRequirements().values().stream().flatMap(List::stream).filter(Objects::nonNull) + .filter(def -> uniqueId.equals(def.getUniqueId())).findFirst().orElse(null); + } + private String retrieveCapabilityUid(String name, CapabilityOwner capabilityOwner) { - return capabilityOwner.getCapabilities().values() - .stream() - .flatMap(List::stream) - .filter(Objects::nonNull) - .filter(def -> name.equals(def.getName())) - .findFirst() - .map(CapabilityDefinition::getUniqueId) - .orElse(null); + return capabilityOwner.getCapabilities().values().stream().flatMap(List::stream).filter(Objects::nonNull) + .filter(def -> name.equals(def.getName())).findFirst().map(CapabilityDefinition::getUniqueId).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); + return vfc.getRequirements().values().stream().flatMap(List::stream).filter(Objects::nonNull).filter(def -> name.equals(def.getName())) + .findFirst().map(RequirementDefinition::getUniqueId).orElse(null); } } 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 index 9150e5e91e..ab9b0a5b92 100644 --- 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 @@ -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. @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.path; import fj.data.Either; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; @@ -34,23 +36,17 @@ import org.openecomp.sdc.common.log.wrappers.Logger; 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 = Logger.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; + private static final int PATH_NAME_LENGTH = 200; + private static final int PROTOCOL_LENGTH = 200; + private static final int DESTINATION_PORT_LENGTH = 200; - public void validateForwardingPaths(Collection paths, - String serviceId, boolean isUpdate) { + public void validateForwardingPaths(Collection paths, String serviceId, boolean isUpdate) { for (ForwardingPathDataDefinition path : paths) { validateForwardingPath(path, serviceId, isUpdate); } @@ -64,12 +60,11 @@ public class ForwardingPathValidator { } private void validateDestinationPortNumber(ForwardingPathDataDefinition dataDefinition) { - if (dataDefinition.getDestinationPortNumber() != null && - dataDefinition.getDestinationPortNumber().length() > DESTINATION_PORT_LENGTH ) { - logger.debug("Forwarding path destination port {} too long, , maximum allowed 200 characters ", - dataDefinition.getDestinationPortNumber()); - throw new ByActionStatusComponentException(ActionStatus - .FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH, dataDefinition.getDestinationPortNumber()); + if (dataDefinition.getDestinationPortNumber() != null && dataDefinition.getDestinationPortNumber().length() > DESTINATION_PORT_LENGTH) { + logger + .debug("Forwarding path destination port {} too long, , maximum allowed 200 characters ", dataDefinition.getDestinationPortNumber()); + throw new ByActionStatusComponentException(ActionStatus.FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH, + dataDefinition.getDestinationPortNumber()); } } @@ -80,15 +75,12 @@ public class ForwardingPathValidator { } } - private void validateName(ForwardingPathDataDefinition dataDefinition, - ResponseFormatManager responseFormatManager, - String serviceId, boolean isUpdate) { + private void validateName(ForwardingPathDataDefinition dataDefinition, ResponseFormatManager responseFormatManager, String serviceId, + boolean isUpdate) { String pathName = dataDefinition.getName(); validatePathNameIfEmpty(responseFormatManager, pathName); - validatePathNameLength(responseFormatManager, pathName); - - Boolean isPathNameUniqueResponse = validatePathIfUnique(dataDefinition, serviceId, isUpdate, responseFormatManager ); + Boolean isPathNameUniqueResponse = validatePathIfUnique(dataDefinition, serviceId, isUpdate, responseFormatManager); if (!isPathNameUniqueResponse) { logger.debug("Forwarding path name {} already in use ", dataDefinition.getName()); throw new ByActionStatusComponentException(ActionStatus.FORWARDING_PATH_NAME_ALREADY_IN_USE, dataDefinition.getName()); @@ -109,44 +101,34 @@ public class ForwardingPathValidator { } } - - private Boolean validatePathIfUnique(ForwardingPathDataDefinition dataDefinition, String serviceId, - boolean isUpdate, ResponseFormatManager responseFormatManager) { + private Boolean validatePathIfUnique(ForwardingPathDataDefinition dataDefinition, String serviceId, boolean isUpdate, + ResponseFormatManager responseFormatManager) { boolean isPathNameUnique = false; ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreServicePath(false); - Either forwardingPathOrigin = toscaOperationFacade - .getToscaElement(serviceId, filter); - if (forwardingPathOrigin.isRight()){ + Either forwardingPathOrigin = toscaOperationFacade.getToscaElement(serviceId, filter); + if (forwardingPathOrigin.isRight()) { throw new ByActionStatusComponentException(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())) { + 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())){ + if (entry.getKey().equals(dataDefinition.getUniqueId()) && !pathNames.values().contains(dataDefinition.getName())) { isPathNameUnique = true; } } - } - else - if (!pathNames.values().contains(dataDefinition.getName())){ + } else if (!pathNames.values().contains(dataDefinition.getName())) { isPathNameUnique = true; } - return isPathNameUnique; } protected ResponseFormatManager getResponseFormatManager() { return ResponseFormatManager.getInstance(); } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java index c7d9cfb841..40a6223bd0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.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. @@ -17,10 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getInputAnnotations; + import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; import org.openecomp.sdc.be.datatypes.elements.Annotation; @@ -37,15 +44,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getInputAnnotations; - @org.springframework.stereotype.Component public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDeclarator { @@ -54,7 +52,9 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; private final ExceptionUtils exceptionUtils; - public ComponentInstanceInputPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ExceptionUtils exceptionUtils) { + public ComponentInstanceInputPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, + ToscaOperationFacade toscaOperationFacade, + ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ExceptionUtils exceptionUtils) { super(componentsUtils, propertyOperation); this.toscaOperationFacade = toscaOperationFacade; this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; @@ -67,8 +67,10 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec } @Override - public Either updatePropertiesValues(Component component, String cmptInstanceId, List properties) { - log.debug("#updatePropertiesValues - updating component instance inputs for instance {} on component {}", cmptInstanceId, component.getUniqueId()); + public 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); } @@ -82,7 +84,7 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec @Override public void addPropertiesListToInput(ComponentInstanceInput declaredProp, InputDefinition input) { List inputsValueList = input.getInputs(); - if(inputsValueList == null) { + if (inputsValueList == null) { inputsValueList = new ArrayList<>(); // adding the property with the new value for UI } inputsValueList.add(declaredProp); @@ -91,26 +93,33 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec @Override public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { - List componentInstanceInputsByInputId = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, input.getUniqueId()); + List componentInstanceInputsByInputId = componentInstanceBusinessLogic + .getComponentInstanceInputsByInputId(component, input.getUniqueId()); if (isEmpty(componentInstanceInputsByInputId)) { return StorageOperationStatus.OK; } - componentInstanceInputsByInputId.forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath())); - return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), componentInstanceInputsByInputId); + componentInstanceInputsByInputId + .forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath())); + return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), + componentInstanceInputsByInputId); } @Override public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition input) { - List componentInstanceInputsByInputId = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, input.getUniqueId()); + List componentInstanceInputsByInputId = componentInstanceBusinessLogic + .getComponentInstanceInputsByInputId(component, input.getUniqueId()); if (isEmpty(componentInstanceInputsByInputId)) { return StorageOperationStatus.OK; } - componentInstanceInputsByInputId.forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath())); - return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), componentInstanceInputsByInputId); + componentInstanceInputsByInputId + .forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath())); + return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), + componentInstanceInputsByInputId); } @Override - InputDefinition createInputFromProperty(String componentId, ComponentInstance propertiesOwner, String inputName, ComponentInstancePropInput propInput, PropertyDataDefinition prop) { + InputDefinition createInputFromProperty(String componentId, ComponentInstance propertiesOwner, String inputName, + ComponentInstancePropInput propInput, PropertyDataDefinition prop) { InputDefinition inputFromProperty = super.createInputFromProperty(componentId, propertiesOwner, inputName, propInput, prop); Component propertiesOwnerNodeType = getInstanceOriginType(propertiesOwner); enrichInputWithAnnotations(prop, inputFromProperty, propertiesOwnerNodeType); @@ -119,15 +128,14 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec private void enrichInputWithAnnotations(PropertyDataDefinition prop, InputDefinition inputFromProperty, Component propertiesOwnerNodeType) { List inputAnnotations = getInputAnnotations(propertiesOwnerNodeType, prop.getName()); - if(!isEmpty(inputAnnotations)){ + if (!isEmpty(inputAnnotations)) { inputFromProperty.setAnnotations(inputAnnotations); } } private Component getInstanceOriginType(ComponentInstance propertiesOwner) { - return toscaOperationFacade.getToscaElement(propertiesOwner.getActualComponentUid(), getFilterComponentInputs()) - .left() - .on(err -> exceptionUtils.rollBackAndThrow(err, propertiesOwner.getActualComponentUid())); + return toscaOperationFacade.getToscaElement(propertiesOwner.getActualComponentUid(), getFilterComponentInputs()).left() + .on(err -> exceptionUtils.rollBackAndThrow(err, propertiesOwner.getActualComponentUid())); } private ComponentParametersView getFilterComponentInputs() { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java index 1d8a23ec55..3c5ca44b33 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.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. @@ -17,10 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.utils.PropertiesUtils; @@ -36,12 +40,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -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 ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarator { @@ -49,7 +47,9 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat private ToscaOperationFacade toscaOperationFacade; private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - public ComponentInstancePropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { + public ComponentInstancePropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, + ToscaOperationFacade toscaOperationFacade, + ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { super(componentsUtils, propertyOperation); this.toscaOperationFacade = toscaOperationFacade; this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; @@ -61,8 +61,10 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat } @Override - public Either updatePropertiesValues(Component component, String cmptInstanceId, List properties) { - log.debug("#updatePropertiesValues - updating component instance properties for instance {} on component {}", cmptInstanceId, component.getUniqueId()); + public 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); } @@ -76,7 +78,7 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat @Override public void addPropertiesListToInput(ComponentInstanceProperty declaredProp, InputDefinition input) { List propertiesList = input.getProperties(); - if(propertiesList == null) { + if (propertiesList == null) { propertiesList = new ArrayList<>(); // adding the property with the new value for UI } propertiesList.add(declaredProp); @@ -85,44 +87,44 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat @Override public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { - - Optional propertyByInputId = PropertiesUtils.getPropertyByInputId(component, - input.getUniqueId()); - if(propertyByInputId.isPresent()) { - List capabilityPropertyDeclaredAsInput = - PropertiesUtils.getCapabilityProperty(propertyByInputId.get(), input.getUniqueId()); - capabilityPropertyDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDeleteOfCapProp(input, - cmptInstanceProperty)); - - Optional propertyCapabilityOptional = PropertiesUtils.getPropertyCapabilityOfChildInstance( - capabilityPropertyDeclaredAsInput.get(0).getParentUniqueId(), component.getCapabilities()); - if(!propertyCapabilityOptional.isPresent()) { + Optional propertyByInputId = PropertiesUtils.getPropertyByInputId(component, input.getUniqueId()); + if (propertyByInputId.isPresent()) { + List capabilityPropertyDeclaredAsInput = PropertiesUtils + .getCapabilityProperty(propertyByInputId.get(), input.getUniqueId()); + capabilityPropertyDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDeleteOfCapProp(input, cmptInstanceProperty)); + Optional propertyCapabilityOptional = PropertiesUtils + .getPropertyCapabilityOfChildInstance(capabilityPropertyDeclaredAsInput.get(0).getParentUniqueId(), component.getCapabilities()); + if (!propertyCapabilityOptional.isPresent()) { return StorageOperationStatus.OK; } - - return toscaOperationFacade.updateInstanceCapabilityProperty(component, input.getInstanceUniqueId(), - capabilityPropertyDeclaredAsInput.get(0), propertyCapabilityOptional.get() ); + return toscaOperationFacade + .updateInstanceCapabilityProperty(component, input.getInstanceUniqueId(), capabilityPropertyDeclaredAsInput.get(0), + propertyCapabilityOptional.get()); } else { List componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic - .getComponentInstancePropertiesByInputId(component, input.getUniqueId()); + .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 + .forEach(cmptInstanceProperty -> prepareValueBeforeDelete(input, cmptInstanceProperty, cmptInstanceProperty.getPath())); + return toscaOperationFacade + .updateComponentInstanceProperties(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(), componentInstancePropertiesDeclaredAsInput); } } @Override public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition input) { - List componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, input.getUniqueId()); + 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); + 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/ComponentPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java index 14479d4263..dc5b95fd55 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java @@ -13,10 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.property; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; @@ -30,183 +33,140 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - @org.springframework.stereotype.Component public class ComponentPropertyDeclarator extends DefaultPropertyDeclarator { - private ToscaOperationFacade toscaOperationFacade; - PropertyBusinessLogic propertyBL; - - - public ComponentPropertyDeclarator(ComponentsUtils componentsUtils, - PropertyOperation propertyOperation, - ToscaOperationFacade toscaOperationFacade, - PropertyBusinessLogic propertyBL) { - super(componentsUtils, propertyOperation); - this.toscaOperationFacade = toscaOperationFacade; - this.propertyBL = propertyBL; - } + PropertyBusinessLogic propertyBL; + private ToscaOperationFacade toscaOperationFacade; - @Override - public PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { - return new PropertyDataDefinition(prop); - } - - @Override - public Either updatePropertiesValues(Component component, - String propertiesOwnerId, - List properties) { - if(CollectionUtils.isNotEmpty(properties)) { - for(PropertyDataDefinition property : properties) { - Either - storageStatus = toscaOperationFacade - .updatePropertyOfComponent(component, new PropertyDefinition(property)); - if(storageStatus.isRight()) { - return Either.right(storageStatus.right().value()); - } - } + public ComponentPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, + ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBL) { + super(componentsUtils, propertyOperation); + this.toscaOperationFacade = toscaOperationFacade; + this.propertyBL = propertyBL; } - return Either.left(properties); - } - - @Override - public Optional resolvePropertiesOwner(Component component, String propertiesOwnerId) { - return Optional.of(component); - } - @Override - public void addPropertiesListToInput(PropertyDataDefinition declaredProp, - InputDefinition input) { - - List propertiesList = input.getProperties(); - if(propertiesList == null) { - propertiesList = new ArrayList<>(); // adding the property with the new value for UI + @Override + public PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { + return new PropertyDataDefinition(prop); } - propertiesList.add(new ComponentInstanceProperty(declaredProp)); - input.setProperties(propertiesList); - } - - @Override - public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, - InputDefinition input) { - PropertyDefinition propertyDefinition = new PropertyDefinition(input); - if(propertyBL.isPropertyUsedByOperation(component, propertyDefinition)) { - return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION; - } - - Optional propertyToUpdateCandidate = - getDeclaredPropertyByInputId(component, input.getUniqueId()); - - if(propertyToUpdateCandidate.isPresent()) { - PropertyDefinition propertyToUpdate = propertyToUpdateCandidate.get(); - return unDeclareInput(component, input, propertyToUpdate); + @Override + public Either updatePropertiesValues(Component component, String propertiesOwnerId, + List properties) { + if (CollectionUtils.isNotEmpty(properties)) { + for (PropertyDataDefinition property : properties) { + Either storageStatus = toscaOperationFacade + .updatePropertyOfComponent(component, new PropertyDefinition(property)); + if (storageStatus.isRight()) { + return Either.right(storageStatus.right().value()); + } + } + } + return Either.left(properties); } - - return StorageOperationStatus.OK; - } - - @Override - public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, - InputDefinition input) { - PropertyDefinition propertyDefinition = new PropertyDefinition(input); - - if(propertyBL.isPropertyUsedByOperation(component, propertyDefinition)) { - return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION; + @Override + public Optional resolvePropertiesOwner(Component component, String propertiesOwnerId) { + return Optional.of(component); } - Optional> propertyToUpdateCandidate = - getDeclaredPropertiesByInputId(component, input.getUniqueId()); - - if(propertyToUpdateCandidate.isPresent()) { - List propertiesToUpdate = propertyToUpdateCandidate.get(); - if (!propertiesToUpdate.isEmpty()) { - return unDeclareInputs(component, input, propertiesToUpdate); - } + @Override + public void addPropertiesListToInput(PropertyDataDefinition declaredProp, 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); } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus unDeclareInputs(Component component, - InputDefinition input, - List propertiesToUpdate) { - for (PropertyDefinition propertyToUpdate : propertiesToUpdate) { - StorageOperationStatus storageOperationStatus = unDeclareInput(component, input, propertyToUpdate); - if (StorageOperationStatus.OK != storageOperationStatus) { - return storageOperationStatus; - } + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { + PropertyDefinition propertyDefinition = new PropertyDefinition(input); + if (propertyBL.isPropertyUsedByOperation(component, propertyDefinition)) { + return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION; + } + Optional propertyToUpdateCandidate = getDeclaredPropertyByInputId(component, input.getUniqueId()); + if (propertyToUpdateCandidate.isPresent()) { + PropertyDefinition propertyToUpdate = propertyToUpdateCandidate.get(); + return unDeclareInput(component, input, propertyToUpdate); + } + return StorageOperationStatus.OK; } - return StorageOperationStatus.OK; - } - private StorageOperationStatus unDeclareInput(Component component, - InputDefinition input, - PropertyDefinition propertyToUpdate) { - prepareValueBeforeDelete(input, propertyToUpdate, Collections.emptyList()); - propertyToUpdate.setValue(input.getDefaultValue()); - Either status = toscaOperationFacade - .updatePropertyOfComponent(component, propertyToUpdate); - if(status.isRight()) { - return status.right().value(); + @Override + public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition input) { + PropertyDefinition propertyDefinition = new PropertyDefinition(input); + if (propertyBL.isPropertyUsedByOperation(component, propertyDefinition)) { + return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION; + } + Optional> propertyToUpdateCandidate = getDeclaredPropertiesByInputId(component, input.getUniqueId()); + if (propertyToUpdateCandidate.isPresent()) { + List propertiesToUpdate = propertyToUpdateCandidate.get(); + if (!propertiesToUpdate.isEmpty()) { + return unDeclareInputs(component, input, propertiesToUpdate); + } + } + return StorageOperationStatus.OK; } - return StorageOperationStatus.OK; - } - - private Optional getDeclaredPropertyByInputId(Component component, String inputId) { - List properties = component.getProperties(); - - if (CollectionUtils.isEmpty(properties)) { - return Optional.empty(); + private StorageOperationStatus unDeclareInputs(Component component, InputDefinition input, List propertiesToUpdate) { + for (PropertyDefinition propertyToUpdate : propertiesToUpdate) { + StorageOperationStatus storageOperationStatus = unDeclareInput(component, input, propertyToUpdate); + if (StorageOperationStatus.OK != storageOperationStatus) { + return storageOperationStatus; + } + } + return StorageOperationStatus.OK; } - for (PropertyDefinition propertyDefinition : properties) { - List getInputValues = propertyDefinition.getGetInputValues(); - if (CollectionUtils.isEmpty(getInputValues)) { - continue; - } - - Optional getInputCandidate = - getInputValues.stream().filter(getInput -> getInput.getInputId().equals(inputId)).findAny(); - - if (getInputCandidate.isPresent()) { - return Optional.of(propertyDefinition); - } + private StorageOperationStatus unDeclareInput(Component component, InputDefinition input, PropertyDefinition propertyToUpdate) { + prepareValueBeforeDelete(input, propertyToUpdate, Collections.emptyList()); + propertyToUpdate.setValue(input.getDefaultValue()); + Either status = toscaOperationFacade.updatePropertyOfComponent(component, propertyToUpdate); + if (status.isRight()) { + return status.right().value(); + } + return StorageOperationStatus.OK; } - return Optional.empty(); - } - - private Optional> getDeclaredPropertiesByInputId(Component component, - String inputId) { - List properties = component.getProperties(); - List propertiesToUpdate = new ArrayList<>(); - - if(CollectionUtils.isEmpty(properties)) { - return Optional.empty(); + private Optional getDeclaredPropertyByInputId(Component component, String inputId) { + List properties = component.getProperties(); + if (CollectionUtils.isEmpty(properties)) { + return Optional.empty(); + } + for (PropertyDefinition propertyDefinition : properties) { + List getInputValues = propertyDefinition.getGetInputValues(); + if (CollectionUtils.isEmpty(getInputValues)) { + continue; + } + Optional getInputCandidate = getInputValues.stream() + .filter(getInput -> getInput.getInputId().equals(inputId)).findAny(); + if (getInputCandidate.isPresent()) { + return Optional.of(propertyDefinition); + } + } + return Optional.empty(); } - for(PropertyDefinition propertyDefinition : properties) { - List getInputValues = propertyDefinition.getGetInputValues(); - if(CollectionUtils.isEmpty(getInputValues)) { - continue; - } - - Optional getInputCandidate = - getInputValues.stream().filter(getInput -> getInput.getInputId().equals(inputId)) - .findAny(); - - if(getInputCandidate.isPresent()) { - propertiesToUpdate.add(propertyDefinition); - } + private Optional> getDeclaredPropertiesByInputId(Component component, String inputId) { + List properties = component.getProperties(); + List propertiesToUpdate = new ArrayList<>(); + if (CollectionUtils.isEmpty(properties)) { + return Optional.empty(); + } + for (PropertyDefinition propertyDefinition : properties) { + List getInputValues = propertyDefinition.getGetInputValues(); + if (CollectionUtils.isEmpty(getInputValues)) { + continue; + } + Optional getInputCandidate = getInputValues.stream() + .filter(getInput -> getInput.getInputId().equals(inputId)).findAny(); + if (getInputCandidate.isPresent()) { + propertiesToUpdate.add(propertyDefinition); + } + } + return Optional.of(propertiesToUpdate); } - - return Optional.of(propertiesToUpdate); - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java index 9d65a667fe..575a54d894 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.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. @@ -17,11 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property; +import static org.openecomp.sdc.common.api.Constants.GET_INPUT; +import static org.openecomp.sdc.common.api.Constants.GET_POLICY; + import com.google.gson.Gson; import fj.data.Either; +import java.util.ArrayList; +import java.util.Arrays; +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.Optional; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -48,30 +61,16 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.yaml.snakeyaml.Yaml; -import java.util.ArrayList; -import java.util.Arrays; -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.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.common.api.Constants.GET_INPUT; -import static org.openecomp.sdc.common.api.Constants.GET_POLICY; - -public abstract class DefaultPropertyDeclarator implements PropertyDeclarator { +public abstract class DefaultPropertyDeclarator implements + PropertyDeclarator { private static final Logger log = Logger.getLogger(DefaultPropertyDeclarator.class); private static final short LOOP_PROTECTION_LEVEL = 10; private static final String UNDERSCORE = "_"; + private static final String GET_INPUT_INDEX = "INDEX"; private final Gson gson = new Gson(); private ComponentsUtils componentsUtils; private PropertyOperation propertyOperation; - private static final String GET_INPUT_INDEX = "INDEX"; public DefaultPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation) { this.componentsUtils = componentsUtils; @@ -79,34 +78,40 @@ public abstract class DefaultPropertyDeclarator, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List propsToDeclare) { - log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId); + 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))); + .map(propertyOwner -> declarePropertiesAsInputs(component, propertyOwner, propsToDeclare)) + .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId))); } protected abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop); - protected abstract Either updatePropertiesValues(Component component, String propertiesOwnerId, List properties); + protected abstract Either updatePropertiesValues(Component component, String propertiesOwnerId, + List properties); protected abstract Optional resolvePropertiesOwner(Component component, String propertiesOwnerId); protected abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, InputDefinition input); @Override - public Either, StorageOperationStatus> declarePropertiesAsPolicies(Component component, - String propertiesOwnerId, - List propsToDeclare) { - log.debug("#declarePropertiesAsPolicies - declaring properties as policies for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId); + public Either, StorageOperationStatus> declarePropertiesAsPolicies(Component component, String propertiesOwnerId, + List propsToDeclare) { + log.debug("#declarePropertiesAsPolicies - declaring properties as policies for component {} from properties owner {}", + component.getUniqueId(), propertiesOwnerId); return resolvePropertiesOwner(component, propertiesOwnerId) - .map(propertyOwner -> declarePropertiesAsPolicies(component, propertyOwner, propsToDeclare)) - .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId))); + .map(propertyOwner -> declarePropertiesAsPolicies(component, propertyOwner, propsToDeclare)) + .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId))); } @Override - public Either declarePropertiesAsListInput(Component component, String propertiesOwnerId, List propsToDeclare, InputDefinition input) { - log.debug("#declarePropertiesAsListInput - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId); + public Either declarePropertiesAsListInput(Component component, String propertiesOwnerId, + List propsToDeclare, + InputDefinition input) { + log.debug("#declarePropertiesAsListInput - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), + propertiesOwnerId); Optional propertyOwner = resolvePropertiesOwner(component, propertiesOwnerId); if (propertyOwner.isPresent()) { return declarePropertiesAsListInput(component, propertyOwner.get(), propsToDeclare, input); @@ -119,11 +124,12 @@ public abstract class DefaultPropertyDeclarator, StorageOperationStatus> declarePropertiesAsPolicies(Component component, PROPERTYOWNER propertiesOwner, List propsToDeclare) { - PropertiesDeclarationData policyProperties = createPoliciesAndOverridePropertiesValues(propertiesOwner.getUniqueId(), propertiesOwner, propsToDeclare); - return updatePropertiesValues(component, propertiesOwner.getUniqueId(), policyProperties.getPropertiesToUpdate()) - .left() - .map(updatePropsRes -> policyProperties.getPoliciesToCreate()); + private Either, StorageOperationStatus> declarePropertiesAsPolicies(Component component, PROPERTYOWNER propertiesOwner, + List propsToDeclare) { + PropertiesDeclarationData policyProperties = createPoliciesAndOverridePropertiesValues(propertiesOwner.getUniqueId(), propertiesOwner, + propsToDeclare); + return updatePropertiesValues(component, propertiesOwner.getUniqueId(), policyProperties.getPropertiesToUpdate()).left() + .map(updatePropsRes -> policyProperties.getPoliciesToCreate()); } private StorageOperationStatus onPropertiesOwnerNotFound(String componentId, String propertiesOwnerId) { @@ -131,69 +137,59 @@ public abstract class DefaultPropertyDeclarator, StorageOperationStatus> declarePropertiesAsInputs(Component component, PROPERTYOWNER propertiesOwner, List propsToDeclare) { + private Either, StorageOperationStatus> declarePropertiesAsInputs(Component component, PROPERTYOWNER propertiesOwner, + List propsToDeclare) { PropertiesDeclarationData inputsProperties = createInputsAndOverridePropertiesValues(component, propertiesOwner, propsToDeclare); - return updatePropertiesValues(component, propertiesOwner.getUniqueId(), inputsProperties.getPropertiesToUpdate()) - .left() - .map(updatePropsRes -> inputsProperties.getInputsToCreate()); + return updatePropertiesValues(component, propertiesOwner.getUniqueId(), inputsProperties.getPropertiesToUpdate()).left() + .map(updatePropsRes -> inputsProperties.getInputsToCreate()); } - private PropertiesDeclarationData createPoliciesAndOverridePropertiesValues(String componentId, PROPERTYOWNER propertiesOwner, List propsToDeclare) { + + private PropertiesDeclarationData createPoliciesAndOverridePropertiesValues(String componentId, PROPERTYOWNER propertiesOwner, + List propsToDeclare) { List declaredProperties = new ArrayList<>(); List policies = new ArrayList<>(); propsToDeclare.forEach(property -> policies.add(declarePropertyPolicy(componentId, declaredProperties, property))); return new PropertiesDeclarationData(null, policies, declaredProperties); } - private PolicyDefinition declarePropertyPolicy(String componentId, List declaredProperties, - ComponentInstancePropInput propInput) { + private PolicyDefinition declarePropertyPolicy(String componentId, List declaredProperties, ComponentInstancePropInput propInput) { PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput); propInput.setOwnerId(null); propInput.setParentUniqueId(null); - PolicyDefinition policyDefinition = new PolicyDefinition(prop); policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentId, prop.getName())); policyDefinition.setInputPath(prop.getName()); policyDefinition.setInstanceUniqueId(componentId); policyDefinition.setPropertyId(prop.getUniqueId()); - changePropertyValueToGetPolicy(prop, policyDefinition); PROPERTYTYPE declaredProperty = createDeclaredProperty(prop); - - - if(!declaredProperties.contains(declaredProperty)){ + if (!declaredProperties.contains(declaredProperty)) { declaredProperties.add(declaredProperty); } - return policyDefinition; } private void changePropertyValueToGetPolicy(PropertyDataDefinition prop, PolicyDefinition policyDefinition) { JSONObject jsonObject = new JSONObject(); - String origValue = Objects.isNull(prop.getValue()) ? prop.getDefaultValue() : prop.getValue(); jsonObject.put(GET_POLICY, null); prop.setValue(jsonObject.toJSONString()); policyDefinition.setValue(jsonObject.toJSONString()); - - if(CollectionUtils.isEmpty(prop.getGetPolicyValues())){ + if (CollectionUtils.isEmpty(prop.getGetPolicyValues())) { prop.setGetPolicyValues(new ArrayList<>()); } List getPolicyValues = prop.getGetPolicyValues(); - GetPolicyValueDataDefinition getPolicyValueDataDefinition = new GetPolicyValueDataDefinition(); getPolicyValueDataDefinition.setPolicyId(policyDefinition.getUniqueId()); getPolicyValueDataDefinition.setPropertyName(prop.getName()); - getPolicyValueDataDefinition.setOrigPropertyValue(origValue); - getPolicyValues.add(getPolicyValueDataDefinition); - policyDefinition.setGetPolicyValues(getPolicyValues); - } - - private Either declarePropertiesAsListInput(Component component, PROPERTYOWNER propertiesOwner, List propsToDeclare, InputDefinition input) { + private Either declarePropertiesAsListInput(Component component, PROPERTYOWNER propertiesOwner, + List propsToDeclare, + InputDefinition input) { List declaredProperties = new ArrayList<>(); for (ComponentInstancePropInput propInput : propsToDeclare) { if (StringUtils.isNotEmpty(propInput.getPropertiesName()) && propInput.getInput() != null) { @@ -202,11 +198,9 @@ public abstract class DefaultPropertyDeclarator input); + return updatePropertiesValues(component, propertiesOwner.getUniqueId(), declaredProperties).left().map(x -> input); } - private PropertiesDeclarationData createInputsAndOverridePropertiesValues(Component component, PROPERTYOWNER propertiesOwner, List propsToDeclare) { + private PropertiesDeclarationData createInputsAndOverridePropertiesValues(Component component, PROPERTYOWNER propertiesOwner, + List propsToDeclare) { List declaredProperties = new ArrayList<>(); List createdInputs = propsToDeclare.stream() - .map(propInput -> declarePropertyInput(component, propertiesOwner, declaredProperties, propInput)) - .collect(Collectors.toList()); + .map(propInput -> declarePropertyInput(component, propertiesOwner, declaredProperties, propInput)).collect(Collectors.toList()); return new PropertiesDeclarationData(createdInputs, null, declaredProperties); } - private InputDefinition declarePropertyInput(Component component, PROPERTYOWNER propertiesOwner, List declaredProperties, ComponentInstancePropInput propInput) { + private InputDefinition declarePropertyInput(Component component, PROPERTYOWNER propertiesOwner, List declaredProperties, + ComponentInstancePropInput propInput) { PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput); InputDefinition inputDefinition = createInput(component, propertiesOwner, propInput, prop); PROPERTYTYPE declaredProperty = createDeclaredProperty(prop); - if(!declaredProperties.contains(declaredProperty)){ + if (!declaredProperties.contains(declaredProperty)) { declaredProperties.add(declaredProperty); } addPropertiesListToInput(declaredProperty, inputDefinition); return inputDefinition; } - private InputDefinition createInput(Component component, PROPERTYOWNER propertiesOwner, - ComponentInstancePropInput propInput, PropertyDataDefinition prop) { + private InputDefinition createInput(Component component, PROPERTYOWNER propertiesOwner, ComponentInstancePropInput propInput, + PropertyDataDefinition prop) { String generatedInputPrefix = propertiesOwner.getNormalizedName(); if (propertiesOwner.getUniqueId().equals(propInput.getParentUniqueId())) { //Creating input from property create on self using add property..Do not add the prefix generatedInputPrefix = null; } - - Optional propertyCapability = PropertiesUtils.getPropertyCapabilityOfChildInstance(propInput - .getParentUniqueId(), component.getCapabilities()); + Optional propertyCapability = PropertiesUtils + .getPropertyCapabilityOfChildInstance(propInput.getParentUniqueId(), component.getCapabilities()); if (propertyCapability.isPresent()) { String capName = propertyCapability.get().getName(); - if(capName.contains(".")) { + if (capName.contains(".")) { capName = capName.replaceAll("\\.", UNDERSCORE); } - generatedInputPrefix = generatedInputPrefix == null || generatedInputPrefix.isEmpty()? - capName : generatedInputPrefix + UNDERSCORE + capName; + generatedInputPrefix = + generatedInputPrefix == null || generatedInputPrefix.isEmpty() ? capName : generatedInputPrefix + UNDERSCORE + capName; } - String generatedInputName = generateInputName(generatedInputPrefix, propInput); log.debug("createInput: propOwner.uniqueId={}, propInput.parentUniqueId={}", propertiesOwner.getUniqueId(), propInput.getParentUniqueId()); return createInputFromProperty(component.getUniqueId(), propertiesOwner, generatedInputName, propInput, prop); @@ -272,56 +263,50 @@ public abstract class DefaultPropertyDeclarator propertiesToCreate, ComponentInstancePropInput propInput) { - Optional resolvedProperty = propertiesToCreate.stream() - .filter(p -> p.getName().equals(propInput.getName())) - .findFirst(); + Optional resolvedProperty = propertiesToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst(); return resolvedProperty.isPresent() ? resolvedProperty.get() : propInput; } - InputDefinition createInputFromProperty(String componentId, PROPERTYOWNER propertiesOwner, String inputName, ComponentInstancePropInput propInput, PropertyDataDefinition prop) { - String propertiesName = propInput.getPropertiesName() ; + InputDefinition createInputFromProperty(String componentId, PROPERTYOWNER 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){ + if (propertiesName != null && !propertiesName.isEmpty() && selectedProp != null) { complexProperty = true; input = new InputDefinition(selectedProp); input.setDefaultValue(selectedProp.getValue()); - }else{ + } else { input = new InputDefinition(prop); input.setDefaultValue(prop.getValue()); } @@ -330,172 +315,125 @@ public abstract class DefaultPropertyDeclarator mappedToscaTemplate = (Map) objValue; createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName); - String json = gson.toJson(mappedToscaTemplate); prop.setValue(json); - } - - }else{ + } else { jsonObject.put(GET_INPUT, input.getName()); prop.setValue(jsonObject.toJSONString()); - } - } - - if(CollectionUtils.isEmpty(prop.getGetInputValues())){ + 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){ + 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{ + return createJSONValueForProperty(i, parsedPropNames, ooj, inputName); + } else { JSONObject res = new JSONObject(); res.put(parsedPropNames[i], ooj); - i --; - res = createJSONValueForProperty (i, parsedPropNames, res, inputName); + 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])){ + 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){ + if (value instanceof Map) { + if (index == inputNames.length - 1) { ((Map) value).put(GET_INPUT, inputName); return (Map) value; - - }else{ + } else { index++; - return createInputValue((Map)value, index, inputNames, inputName); + return createInputValue((Map) value, index, inputNames, inputName); } - }else{ + } else { Map jobProp = new HashMap<>(); - if(index == inputNames.length -1){ + if (index == inputNames.length - 1) { jobProp.put(GET_INPUT, inputName); lhm1.put(inputNames[index], jobProp); return lhm1; - }else{ + } else { lhm1.put(inputNames[index], jobProp); index++; - return createInputValue(jobProp, index, inputNames, inputName); + return createInputValue(jobProp, index, inputNames, inputName); } } - }else{ + } else { Map jobProp = new HashMap<>(); lhm1.put(inputNames[index], jobProp); - if(index == inputNames.length -1){ + if (index == inputNames.length - 1) { jobProp.put(GET_INPUT, inputName); return jobProp; - }else{ + } else { index++; - return createInputValue(jobProp, index, inputNames, inputName); + return createInputValue(jobProp, index, inputNames, inputName); } } } return lhm1; } - private class PropertiesDeclarationData { - private List inputsToCreate; - private List policiesToCreate; - private List propertiesToUpdate; - - PropertiesDeclarationData(List inputsToCreate, List policiesToCreate, List propertiesToUpdate) { - this.inputsToCreate = inputsToCreate; - this.policiesToCreate = policiesToCreate; - this.propertiesToUpdate = propertiesToUpdate; - } - - List getInputsToCreate() { - return inputsToCreate; - } - - public List getPoliciesToCreate() { return policiesToCreate; } - - List getPropertiesToUpdate() { - return propertiesToUpdate; - } - } - - Either prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue, List pathOfComponentInstances) { + Either prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue, + List pathOfComponentInstances) { Either deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue); - Either findDefaultValue = propertyOperation - .findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), - (String) inputValue.getDefaultValue()); + .findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), (String) inputValue.getDefaultValue()); if (findDefaultValue.isRight()) { deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value())))); return deleteEither; - } String defaultValue = findDefaultValue.left().value(); inputValue.setDefaultValue(defaultValue); @@ -503,22 +441,18 @@ public abstract class DefaultPropertyDeclarator prepareValueBeforeDeleteOfCapProp(InputDefinition inputForDelete, - PropertyDataDefinition inputValue) { + Either prepareValueBeforeDeleteOfCapProp(InputDefinition inputForDelete, PropertyDataDefinition inputValue) { Either deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue); inputValue.setDefaultValue(inputForDelete.getDefaultValue()); log.debug("The returned default value in ResourceInstanceProperty is {}", inputForDelete.getDefaultValue()); return deleteEither; } - private Either prepareValueBeforeDelete(InputDefinition inputForDelete, - PropertyDataDefinition inputValue) { + private Either prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue) { 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); @@ -527,32 +461,29 @@ public abstract class DefaultPropertyDeclarator " + result.right().value() - .toString()); //continue, don't break operation + .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(); + Optional op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())) + .findAny(); op.ifPresent(getInputsValues::remove); } inputValue.setGetInputValues(getInputsValues); return deleteEither; } - private void resetInputName(Map lhm1, String inputName){ + 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)) { lhm1.remove(key); } else if (value instanceof Map) { - Map subMap = (Map)value; + Map subMap = (Map) value; resetInputName(subMap, inputName); } else if (value instanceof List && ((List) value).contains(inputName) && key.equals(GET_INPUT)) { lhm1.remove(key); @@ -560,17 +491,17 @@ public abstract class DefaultPropertyDeclarator keysToRemove = new HashSet<>(); // use different set to avoid ConcurrentModificationException - for( Object key : ((Map)toscaElement).keySet() ) { + for (Object key : ((Map) toscaElement).keySet()) { Object value = ((Map) toscaElement).get(key); - ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel ); - if ( ret == null ) + ret = cleanEmptyNestedValuesInMap(value, --loopProtectionLevel); + if (ret == null) { keysToRemove.add(key); + } } Collection set = ((Map) toscaElement).keySet(); - if (CollectionUtils.isNotEmpty(set)) + if (CollectionUtils.isNotEmpty(set)) { set.removeAll(keysToRemove); - - if ( isEmptyNestedMap(toscaElement) ) + } + if (isEmptyNestedMap(toscaElement)) { return null; - } - else + } + } else { return null; + } return toscaElement; } - //@returns true iff map nested maps are all empty //ignores other collection objects - private boolean isEmptyNestedMap(Object element){ + private boolean isEmptyNestedMap(Object element) { boolean isEmpty = true; - if (element != null){ - if ( element instanceof Map ){ - if (MapUtils.isEmpty((Map)element)) + 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 { + for (Object key : ((Map) (element)).keySet()) { + Object value = ((Map) (element)).get(key); + isEmpty &= isEmptyNestedMap(value); } } } else { @@ -628,5 +560,31 @@ public abstract class DefaultPropertyDeclarator inputsToCreate; + private List policiesToCreate; + private List propertiesToUpdate; + + PropertiesDeclarationData(List inputsToCreate, List policiesToCreate, + List propertiesToUpdate) { + this.inputsToCreate = inputsToCreate; + this.policiesToCreate = policiesToCreate; + this.propertiesToUpdate = propertiesToUpdate; + } + + List getInputsToCreate() { + return inputsToCreate; + } + + public List getPoliciesToCreate() { + return policiesToCreate; + } + List getPropertiesToUpdate() { + return propertiesToUpdate; + } + } } 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 index 875321e58e..42a90539b0 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; @@ -28,6 +27,7 @@ public class GetInputUtils { } public static boolean isGetInputValueForInput(GetInputValueDataDefinition inputData, String inputId) { - return inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(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/GroupPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GroupPropertyDeclarator.java index b27cbee037..2700c80cc1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GroupPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GroupPropertyDeclarator.java @@ -17,10 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property; +import static java.util.stream.Collectors.toList; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -33,16 +41,6 @@ import org.openecomp.sdc.be.model.operations.impl.GroupOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static java.util.stream.Collectors.toList; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; - @org.springframework.stereotype.Component public class GroupPropertyDeclarator extends DefaultPropertyDeclarator { @@ -75,26 +73,23 @@ public class GroupPropertyDeclarator extends DefaultPropertyDeclarator propertiesList = input.getProperties(); - if(propertiesList == null) { + 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 getGroupPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId()) - .map(groupProperties -> unDeclareGroupProperties(component, inputForDelete, groupProperties)) - .orElse(StorageOperationStatus.OK); + .map(groupProperties -> unDeclareGroupProperties(component, inputForDelete, groupProperties)).orElse(StorageOperationStatus.OK); } @Override public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition inputForDelete) { return getGroupPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId()) - .map(groupProperties -> unDeclareGroupProperties(component, inputForDelete, groupProperties)) - .orElse(StorageOperationStatus.OK); + .map(groupProperties -> unDeclareGroupProperties(component, inputForDelete, groupProperties)).orElse(StorageOperationStatus.OK); } private StorageOperationStatus unDeclareGroupProperties(Component container, InputDefinition input, GroupProperties groupProperties) { @@ -108,20 +103,13 @@ public class GroupPropertyDeclarator extends DefaultPropertyDeclarator Objects.nonNull(group.getProperties())) - .map(grp -> getGroupPropertiesDeclaredAsInput(grp, inputId)) - .filter(GroupProperties::isNotEmpty) - .findFirst(); + return container.getGroups().stream().filter(group -> Objects.nonNull(group.getProperties())) + .map(grp -> getGroupPropertiesDeclaredAsInput(grp, inputId)).filter(GroupProperties::isNotEmpty).findFirst(); } - private GroupProperties getGroupPropertiesDeclaredAsInput(GroupDefinition group, String inputId) { - List propertyDataDefinitions = group.getProperties() - .stream() - .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId)) - .collect(toList()); + List propertyDataDefinitions = group.getProperties().stream() + .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId)).collect(toList()); return new GroupProperties(group.getUniqueId(), propertyDataDefinitions); } @@ -129,19 +117,17 @@ public class GroupPropertyDeclarator extends DefaultPropertyDeclarator isGetInputValueForInput(getInputVal, inputId)); + return property.getGetInputValues().stream().filter(Objects::nonNull).anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId)); } - private class GroupProperties { + private String groupId; private List properties; GroupProperties(String groupId, List properties) { this.groupId = groupId; - this.properties = (properties == null)? null :new ArrayList<>(properties); + this.properties = (properties == null) ? null : new ArrayList<>(properties); } String getGroupId() { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java index eb7dd688b7..0d07fadb2b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java @@ -19,7 +19,15 @@ */ package org.openecomp.sdc.be.components.property; +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + import fj.data.Either; +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 org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -32,15 +40,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -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 PolicyPropertyDeclarator extends DefaultPropertyDeclarator { @@ -73,26 +72,23 @@ public class PolicyPropertyDeclarator extends DefaultPropertyDeclarator propertiesList = input.getProperties(); - if(propertiesList == null) { + 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); + .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties)).orElse(StorageOperationStatus.OK); } @Override public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition inputForDelete) { return getPolicyPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId()) - .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties)) - .orElse(StorageOperationStatus.OK); + .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties)).orElse(StorageOperationStatus.OK); } private StorageOperationStatus unDeclarePolicyProperties(Component container, InputDefinition input, PolicyProperties policyProperties) { @@ -106,40 +102,31 @@ public class PolicyPropertyDeclarator extends DefaultPropertyDeclarator Objects.nonNull(policy.getProperties())) - .map(policy -> getPolicyPropertiesDeclaredAsInput(policy, inputId)) - .filter(PolicyProperties::isNotEmpty) - .findFirst(); + return container.getPolicies().values().stream().filter(policy -> Objects.nonNull(policy.getProperties())) + .map(policy -> getPolicyPropertiesDeclaredAsInput(policy, inputId)).filter(PolicyProperties::isNotEmpty).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)); + return property.getGetInputValues().stream().filter(Objects::nonNull).anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId)); } private PolicyProperties getPolicyPropertiesDeclaredAsInput(PolicyDefinition policy, String inputId) { - List collect = policy.getProperties() - .stream() - .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId)) - .collect(Collectors.toList()); + List collect = policy.getProperties().stream().filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId)) + .collect(Collectors.toList()); return new PolicyProperties(policy.getUniqueId(), collect); - } private class PolicyProperties { + private String policyId; private List properties; PolicyProperties(String policyId, List properties) { this.policyId = policyId; - this.properties = (properties == null)? null : new ArrayList<>(properties); + this.properties = (properties == null) ? null : new ArrayList<>(properties); } String getPolicyId() { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyConstraintsUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyConstraintsUtils.java index 85370d2211..bd2187616c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyConstraintsUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyConstraintsUtils.java @@ -17,9 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property; +import static java.util.Objects.nonNull; +import static java.util.stream.Collectors.toMap; + +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; @@ -27,41 +31,28 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType; import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; -import java.util.List; -import java.util.Map; - -import static java.util.Objects.nonNull; -import static java.util.stream.Collectors.toMap; - /** * Provides specific functionality for property constraints */ public class PropertyConstraintsUtils { - private PropertyConstraintsUtils(){} + private PropertyConstraintsUtils() { + } public static void validatePropertiesConstraints(Resource newResource, Resource oldResource) { - if(oldResource.getProperties() != null && newResource.getProperties() != null){ - Map oldPropWithConstraints = oldResource.getProperties() - .stream() - .filter(p -> p.getConstraints() != null) - .collect(toMap(PropertyDefinition::getName,p -> p)); - - newResource.getProperties() - .stream() - .filter(p -> p.getConstraints() != null && oldPropWithConstraints.containsKey(p.getName())) - .forEach(p -> validatePropertyConstraints(p.getConstraints(), oldPropWithConstraints.get(p.getName()).getConstraints())); + if (oldResource.getProperties() != null && newResource.getProperties() != null) { + Map oldPropWithConstraints = oldResource.getProperties().stream().filter(p -> p.getConstraints() != null) + .collect(toMap(PropertyDefinition::getName, p -> p)); + newResource.getProperties().stream().filter(p -> p.getConstraints() != null && oldPropWithConstraints.containsKey(p.getName())) + .forEach(p -> validatePropertyConstraints(p.getConstraints(), oldPropWithConstraints.get(p.getName()).getConstraints())); } } private static void validatePropertyConstraints(List newConstraints, List oldConstraints) { - Map oldConstraintsByType = oldConstraints.stream() - .filter(c -> nonNull(c) && nonNull(c.getConstraintType())) - .collect(toMap(PropertyConstraint::getConstraintType, c -> c)); - - newConstraints.stream() - .filter(c -> nonNull(c) && oldConstraintsByType.containsKey(c.getConstraintType())) - .forEach(c -> validatePropertyConstraint(c, oldConstraintsByType.get(c.getConstraintType()))); + Map oldConstraintsByType = oldConstraints.stream() + .filter(c -> nonNull(c) && nonNull(c.getConstraintType())).collect(toMap(PropertyConstraint::getConstraintType, c -> c)); + newConstraints.stream().filter(c -> nonNull(c) && oldConstraintsByType.containsKey(c.getConstraintType())) + .forEach(c -> validatePropertyConstraint(c, oldConstraintsByType.get(c.getConstraintType()))); } private static void validatePropertyConstraint(PropertyConstraint newConstraint, PropertyConstraint currConstraint) { @@ -71,5 +62,4 @@ public class PropertyConstraintsUtils { throw new ByActionStatusComponentException(e.getActionStatus(), e.getParams()); } } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.java index a0d499ddfd..e5367c4e3d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.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. @@ -17,10 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property; +import static org.apache.commons.collections.MapUtils.isNotEmpty; + import fj.data.Either; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.tuple.Pair; import org.openecomp.sdc.be.components.property.propertytopolicydeclarators.ComponentInstancePropertyToPolicyDeclarator; @@ -34,14 +40,6 @@ import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.apache.commons.collections.MapUtils.isNotEmpty; - @org.springframework.stereotype.Component("propertyDeclarationOrchestrator") public class PropertyDeclarationOrchestrator { @@ -57,10 +55,11 @@ public class PropertyDeclarationOrchestrator { private ComponentInstancePropertyToPolicyDeclarator componentInstancePropertyToPolicyDeclarator; public PropertyDeclarationOrchestrator(ComponentInstanceInputPropertyDeclarator componentInstanceInputPropertyDeclarator, - ComponentInstancePropertyDeclarator componentInstancePropertyDeclarator, PolicyPropertyDeclarator policyPropertyDeclarator, - GroupPropertyDeclarator groupPropertyDeclarator, ComponentPropertyDeclarator servicePropertyDeclarator, - ComponentPropertyToPolicyDeclarator componentPropertyToPolicyDeclarator, - ComponentInstancePropertyToPolicyDeclarator componentInstancePropertyToPolicyDeclarator) { + ComponentInstancePropertyDeclarator componentInstancePropertyDeclarator, + PolicyPropertyDeclarator policyPropertyDeclarator, GroupPropertyDeclarator groupPropertyDeclarator, + ComponentPropertyDeclarator servicePropertyDeclarator, + ComponentPropertyToPolicyDeclarator componentPropertyToPolicyDeclarator, + ComponentInstancePropertyToPolicyDeclarator componentInstancePropertyToPolicyDeclarator) { this.componentInstanceInputPropertyDeclarator = componentInstanceInputPropertyDeclarator; this.componentInstancePropertyDeclarator = componentInstancePropertyDeclarator; this.policyPropertyDeclarator = policyPropertyDeclarator; @@ -68,11 +67,14 @@ public class PropertyDeclarationOrchestrator { this.servicePropertyDeclarator = servicePropertyDeclarator; this.componentPropertyToPolicyDeclarator = componentPropertyToPolicyDeclarator; this.componentInstancePropertyToPolicyDeclarator = componentInstancePropertyToPolicyDeclarator; - propertyDeclaratorsToInput = Arrays.asList(componentInstanceInputPropertyDeclarator, componentInstancePropertyDeclarator, policyPropertyDeclarator, groupPropertyDeclarator, servicePropertyDeclarator); + propertyDeclaratorsToInput = Arrays + .asList(componentInstanceInputPropertyDeclarator, componentInstancePropertyDeclarator, policyPropertyDeclarator, groupPropertyDeclarator, + servicePropertyDeclarator); propertyDeclaratorsToPolicy = Arrays.asList(componentPropertyToPolicyDeclarator, componentInstancePropertyToPolicyDeclarator); } - public Either, StorageOperationStatus> declarePropertiesToInputs(Component component, ComponentInstInputsMap componentInstInputsMap) { + public Either, StorageOperationStatus> declarePropertiesToInputs(Component component, + ComponentInstInputsMap componentInstInputsMap) { updatePropertiesConstraints(component, componentInstInputsMap); PropertyDeclarator propertyDeclarator = getPropertyDeclarator(componentInstInputsMap); Pair> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare(); @@ -80,63 +82,63 @@ public class PropertyDeclarationOrchestrator { } private void updatePropertiesConstraints(Component component, ComponentInstInputsMap componentInstInputsMap) { - componentInstInputsMap.getComponentInstanceProperties().forEach((k, v) -> updatePropsConstraints(component.safeGetComponentInstancesProperties(), k, v)); - componentInstInputsMap.getComponentInstanceInputsMap().forEach((k, v) -> updatePropsConstraints(component.safeGetComponentInstancesInputs(), k, v)); + componentInstInputsMap.getComponentInstanceProperties() + .forEach((k, v) -> updatePropsConstraints(component.safeGetComponentInstancesProperties(), k, v)); + componentInstInputsMap.getComponentInstanceInputsMap() + .forEach((k, v) -> updatePropsConstraints(component.safeGetComponentInstancesInputs(), k, v)); componentInstInputsMap.getGroupProperties().forEach((k, v) -> updatePropsConstraints(component.safeGetPolicyProperties(), k, v)); componentInstInputsMap.getPolicyProperties().forEach((k, v) -> updatePropsConstraints(component.safeGetGroupsProperties(), k, v)); } - public Either, StorageOperationStatus> declarePropertiesToPolicies(Component component, ComponentInstInputsMap componentInstInputsMap) { + public Either, StorageOperationStatus> declarePropertiesToPolicies(Component component, + ComponentInstInputsMap componentInstInputsMap) { PropertyDeclarator propertyDeclarator = getPropertyDeclarator(componentInstInputsMap); Pair> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare(); return propertyDeclarator.declarePropertiesAsPolicies(component, propsToDeclare.getLeft(), propsToDeclare.getRight()); } - public Either declarePropertiesToListInput(Component component, ComponentInstInputsMap componentInstInputsMap, InputDefinition input) { + public Either declarePropertiesToListInput(Component component, + ComponentInstInputsMap componentInstInputsMap, + InputDefinition input) { PropertyDeclarator propertyDeclarator = getPropertyDeclarator(componentInstInputsMap); Pair> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare(); log.debug("#declarePropertiesToInputs: componentId={}, propOwnerId={}", component.getUniqueId(), propsToDeclare.getLeft()); return propertyDeclarator.declarePropertiesAsListInput(component, propsToDeclare.getLeft(), propsToDeclare.getRight(), input); } - private void updatePropsConstraints(Map> instancesProperties , String ownerId, List inputs) { - Optional> propertiesOpt = instancesProperties.entrySet() - .stream() - .filter(e -> e.getKey().equals(ownerId)) - .map(Map.Entry::getValue) - .findFirst(); - if(propertiesOpt.isPresent()){ - Map instProps = propertiesOpt.get() - .stream() - .collect(Collectors.toMap(PropertyDataDefinition::getName, p->p)); - inputs.stream() - .filter(i->instProps.containsKey(i.getName())) - .forEach(i->updatePropConstraints(i, instProps.get(i.getName()))); - + private void updatePropsConstraints(Map> instancesProperties, String ownerId, + List inputs) { + Optional> propertiesOpt = instancesProperties.entrySet().stream().filter(e -> e.getKey().equals(ownerId)).map(Map.Entry::getValue) + .findFirst(); + if (propertiesOpt.isPresent()) { + Map instProps = propertiesOpt.get().stream() + .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); + inputs.stream().filter(i -> instProps.containsKey(i.getName())).forEach(i -> updatePropConstraints(i, instProps.get(i.getName()))); } } private void updatePropConstraints(PropertyDataDefinition input, PropertyDataDefinition property) { - if(CollectionUtils.isNotEmpty(property.getPropertyConstraints())){ + if (CollectionUtils.isNotEmpty(property.getPropertyConstraints())) { input.setPropertyConstraints(property.getPropertyConstraints()); - } else if(property.getSchemaProperty() != null && CollectionUtils.isNotEmpty(property.getSchemaProperty().getPropertyConstraints())){ + } else if (property.getSchemaProperty() != null && CollectionUtils.isNotEmpty(property.getSchemaProperty().getPropertyConstraints())) { input.setPropertyConstraints(property.getSchemaProperty().getPropertyConstraints()); } } - public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputToDelete) { - log.debug("#unDeclarePropertiesAsInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), component.getUniqueId()); + log.debug("#unDeclarePropertiesAsInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), + component.getUniqueId()); for (PropertyDeclarator propertyDeclarator : propertyDeclaratorsToInput) { StorageOperationStatus storageOperationStatus = propertyDeclarator.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); + log.debug("#unDeclarePropertiesAsInputs - failed to remove input declaration for input {} on component {}. reason {}", + inputToDelete.getName(), component.getUniqueId(), storageOperationStatus); return storageOperationStatus; } } return StorageOperationStatus.OK; - } + /** * Un declare properties declared as list type input * @@ -145,16 +147,17 @@ public class PropertyDeclarationOrchestrator { * @return */ public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition inputToDelete) { - log.debug("#unDeclarePropertiesAsListInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), component.getUniqueId()); + log.debug("#unDeclarePropertiesAsListInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), + component.getUniqueId()); for (PropertyDeclarator propertyDeclarator : propertyDeclaratorsToInput) { StorageOperationStatus storageOperationStatus = propertyDeclarator.unDeclarePropertiesAsListInputs(component, inputToDelete); if (StorageOperationStatus.OK != storageOperationStatus) { - log.debug("#unDeclarePropertiesAsListInputs - failed to remove input declaration for input {} on component {}. reason {}", inputToDelete.getName(), component.getUniqueId(), storageOperationStatus); + log.debug("#unDeclarePropertiesAsListInputs - failed to remove input declaration for input {} on component {}. reason {}", + inputToDelete.getName(), component.getUniqueId(), storageOperationStatus); return storageOperationStatus; } } return StorageOperationStatus.OK; - } /** @@ -169,20 +172,17 @@ public class PropertyDeclarationOrchestrator { } public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policyToDelete) { - log.debug("#unDeclarePropertiesAsInputs - removing policy declaration for input {} on component {}", policyToDelete - .getName(), component.getUniqueId()); - for(PropertyDeclarator propertyDeclarator : propertyDeclaratorsToPolicy) { - StorageOperationStatus storageOperationStatus = - propertyDeclarator.unDeclarePropertiesAsPolicies(component, policyToDelete); + log.debug("#unDeclarePropertiesAsInputs - removing policy declaration for input {} on component {}", policyToDelete.getName(), + component.getUniqueId()); + for (PropertyDeclarator propertyDeclarator : propertyDeclaratorsToPolicy) { + StorageOperationStatus storageOperationStatus = propertyDeclarator.unDeclarePropertiesAsPolicies(component, policyToDelete); if (StorageOperationStatus.OK != storageOperationStatus) { - log.debug("#unDeclarePropertiesAsInputs - failed to remove policy declaration for policy {} on component {}. reason {}", policyToDelete - .getName(), component.getUniqueId(), storageOperationStatus); + log.debug("#unDeclarePropertiesAsInputs - failed to remove policy declaration for policy {} on component {}. reason {}", + policyToDelete.getName(), component.getUniqueId(), storageOperationStatus); return storageOperationStatus; } } - return StorageOperationStatus.OK; - } private PropertyDeclarator getPropertyDeclarator(ComponentInstInputsMap componentInstInputsMap) { @@ -198,17 +198,15 @@ public class PropertyDeclarationOrchestrator { if (isNotEmpty(componentInstInputsMap.getGroupProperties())) { return groupPropertyDeclarator; } - if(isNotEmpty(componentInstInputsMap.getServiceProperties())) { + if (isNotEmpty(componentInstInputsMap.getServiceProperties())) { return servicePropertyDeclarator; } - if(isNotEmpty(componentInstInputsMap.getComponentPropertiesToPolicies())) { + if (isNotEmpty(componentInstInputsMap.getComponentPropertiesToPolicies())) { return componentPropertyToPolicyDeclarator; } - if(isNotEmpty(componentInstInputsMap.getComponentInstancePropertiesToPolicies())) { + if (isNotEmpty(componentInstInputsMap.getComponentInstancePropertiesToPolicies())) { return componentInstancePropertyToPolicyDeclarator; } throw new IllegalStateException("there are no properties selected for declaration"); - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.java index e067b0cd73..f033c7c356 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.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. @@ -17,69 +17,77 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property; import fj.data.Either; +import java.util.List; 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.PolicyDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import java.util.List; - public interface PropertyDeclarator { /** * creates a list of inputs from the given list of properties and updates the properties accordingly - * @param component the container + * + * @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 + * @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); + 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. + * 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 + * @param input the input to be deleted */ StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input); /** * creates a list of policies from the given list of properties and updates the properties accordingly - * @param component the container + * + * @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 + * @param propsToDeclare the list of properties that are being declared as inputs * @return the list of policies that were created from the given properties */ - Either, StorageOperationStatus> declarePropertiesAsPolicies(Component component, String propertiesOwnerId, List propsToDeclare); + Either, StorageOperationStatus> declarePropertiesAsPolicies(Component component, String propertiesOwnerId, + List propsToDeclare); /** - * returns the values of declared properties to each original state before it was declared as an policy. - * this function is to be called when an policy, that was created by declaring a property, is deleted. + * returns the values of declared properties to each original state before it was declared as an policy. this function is to be called when an + * policy, that was created by declaring a property, is deleted. + * * @param component the container of the input to be deleted - * @param policy the policy to be deleted + * @param policy the policy to be deleted */ StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy); /** - * Updates given list of properties to get values from the specified "list input" with get_input function. - * This function does NOT create "list input", it needs to be created separately. - * @param component the container + * Updates given list of properties to get values from the specified "list input" with get_input function. This function does NOT create "list + * input", it needs to be created separately. + * + * @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 - * @param input the input from which properties get values + * @param propsToDeclare the list of properties that are being declared as inputs + * @param input the input from which properties get values * @return the input same as passed one at 4th argument */ - Either declarePropertiesAsListInput(Component component, String propertiesOwnerId, List propsToDeclare, InputDefinition input); + Either declarePropertiesAsListInput(Component component, String propertiesOwnerId, + List propsToDeclare, + InputDefinition input); /** * Un declare properties declared as list type input + * * @param component the container of the input to be deleted - * @param input the input to be deleted + * @param input the input to be deleted */ StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition input); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java index f8e0ea0912..c07821066a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.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. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property.propertytopolicydeclarators; import fj.data.Either; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.components.property.DefaultPropertyDeclarator; @@ -35,22 +38,16 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - @org.springframework.stereotype.Component -public class ComponentInstancePropertyToPolicyDeclarator extends - DefaultPropertyDeclarator { +public class ComponentInstancePropertyToPolicyDeclarator extends DefaultPropertyDeclarator { - private ToscaOperationFacade toscaOperationFacade; PropertyBusinessLogic propertyBl; + private ToscaOperationFacade toscaOperationFacade; private ComponentInstanceBusinessLogic componentInstanceBl; - public ComponentInstancePropertyToPolicyDeclarator(ComponentsUtils componentsUtils, - PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, - PropertyBusinessLogic propertyBl, ComponentInstanceBusinessLogic componentInstanceBl) { + public ComponentInstancePropertyToPolicyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, + ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBl, + ComponentInstanceBusinessLogic componentInstanceBl) { super(componentsUtils, propertyOperation); this.toscaOperationFacade = toscaOperationFacade; this.propertyBl = propertyBl; @@ -64,9 +61,8 @@ public class ComponentInstancePropertyToPolicyDeclarator extends @Override protected Either updatePropertiesValues(Component component, String componentInstanceId, - List properties) { - Map> - instProperties = Collections.singletonMap(componentInstanceId, properties); + List properties) { + Map> instProperties = Collections.singletonMap(componentInstanceId, properties); return toscaOperationFacade.addComponentInstancePropertiesToComponent(component, instProperties); } @@ -92,16 +88,10 @@ public class ComponentInstancePropertyToPolicyDeclarator extends @Override public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) { - - Optional propertyCandidate = - componentInstanceBl.getComponentInstancePropertyByPolicyId(component, policy); - - - if(propertyCandidate.isPresent()) { - return toscaOperationFacade - .updateComponentInstanceProperty(component, policy.getInstanceUniqueId(), propertyCandidate.get()); + Optional propertyCandidate = componentInstanceBl.getComponentInstancePropertyByPolicyId(component, policy); + if (propertyCandidate.isPresent()) { + return toscaOperationFacade.updateComponentInstanceProperty(component, policy.getInstanceUniqueId(), propertyCandidate.get()); } - return StorageOperationStatus.OK; } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java index 9ac38c3455..a4d2952d5f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.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. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.property.propertytopolicydeclarators; import fj.data.Either; +import java.util.List; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.components.property.DefaultPropertyDeclarator; @@ -35,18 +36,14 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import java.util.List; -import java.util.Optional; - @org.springframework.stereotype.Component public class ComponentPropertyToPolicyDeclarator extends DefaultPropertyDeclarator { - private ToscaOperationFacade toscaOperationFacade; PropertyBusinessLogic propertyBL; - + private ToscaOperationFacade toscaOperationFacade; public ComponentPropertyToPolicyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, - ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBusinessLogic) { + ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBusinessLogic) { super(componentsUtils, propertyOperation); this.toscaOperationFacade = toscaOperationFacade; this.propertyBL = propertyBusinessLogic; @@ -58,20 +55,17 @@ public class ComponentPropertyToPolicyDeclarator extends DefaultPropertyDeclarat } @Override - public Either updatePropertiesValues(Component component, String policyId, - List properties) { - if(CollectionUtils.isNotEmpty(properties)) { - for(PropertyDataDefinition property : properties) { - Either - storageStatus = toscaOperationFacade - .updatePropertyOfComponent(component, new PropertyDefinition(property)); - if(storageStatus.isRight()) { + public Either updatePropertiesValues(Component component, String policyId, List properties) { + if (CollectionUtils.isNotEmpty(properties)) { + for (PropertyDataDefinition property : properties) { + Either storageStatus = toscaOperationFacade + .updatePropertyOfComponent(component, new PropertyDefinition(property)); + if (storageStatus.isRight()) { return Either.right(storageStatus.right().value()); } } } return Either.left(properties); - } @Override @@ -98,66 +92,49 @@ public class ComponentPropertyToPolicyDeclarator extends DefaultPropertyDeclarat @Override public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) { - Optional propertyToUpdateCandidate = - getDeclaredPropertyByPolicyId(component, policy.getUniqueId()); - - if(propertyToUpdateCandidate.isPresent()) { + Optional propertyToUpdateCandidate = getDeclaredPropertyByPolicyId(component, policy.getUniqueId()); + if (propertyToUpdateCandidate.isPresent()) { return unDeclarePolicy(component, propertyToUpdateCandidate.get(), policy); } - return StorageOperationStatus.OK; } private StorageOperationStatus unDeclarePolicy(Component component, PropertyDefinition propertyToUpdate, PolicyDefinition policy) { updatePropertyAfterUndeclaration(propertyToUpdate, policy); - - Either status = toscaOperationFacade - .updatePropertyOfComponent(component, propertyToUpdate); - if(status.isRight()) { + Either status = toscaOperationFacade.updatePropertyOfComponent(component, propertyToUpdate); + if (status.isRight()) { return status.right().value(); } - return StorageOperationStatus.OK; } private void updatePropertyAfterUndeclaration(PropertyDefinition propertyToUpdate, PolicyDefinition policy) { List getPolicyValues = propertyToUpdate.getGetPolicyValues(); Optional getPolicyCandidateToRemove = getPolicyValues.stream() - .filter(getPolicyValue -> getPolicyValue.getPolicyId() - .equals(policy.getUniqueId())) - .findAny(); - + .filter(getPolicyValue -> getPolicyValue.getPolicyId().equals(policy.getUniqueId())).findAny(); getPolicyCandidateToRemove.ifPresent(getPolicyValue -> { getPolicyValues.remove(getPolicyValue); propertyToUpdate.setValue(getPolicyValue.getOrigPropertyValue()); }); } - private Optional getDeclaredPropertyByPolicyId(Component component, - String policyId) { + private Optional getDeclaredPropertyByPolicyId(Component component, String policyId) { List properties = component.getProperties(); - - if(CollectionUtils.isEmpty(properties)) { + if (CollectionUtils.isEmpty(properties)) { return Optional.empty(); } - - for(PropertyDefinition propertyDefinition : properties) { + for (PropertyDefinition propertyDefinition : properties) { List getPolicyValues = propertyDefinition.getGetPolicyValues(); - if(CollectionUtils.isEmpty(getPolicyValues)) { + if (CollectionUtils.isEmpty(getPolicyValues)) { continue; } - - - Optional getPolicyCandidate = - getPolicyValues.stream().filter(getPolicy -> getPolicy.getPolicyId().equals(policyId)).findAny(); - - if(getPolicyCandidate.isPresent()) { + Optional getPolicyCandidate = getPolicyValues.stream() + .filter(getPolicy -> getPolicy.getPolicyId().equals(policyId)).findAny(); + if (getPolicyCandidate.isPresent()) { propertyDefinition.setValue(getPolicyCandidate.get().getOrigPropertyValue()); return Optional.of(propertyDefinition); } } - return Optional.empty(); } - } 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 index 8c951e193e..e1f51cf1ee 100644 --- 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 @@ -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. @@ -17,33 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.scheduledtasks; -import org.openecomp.sdc.common.log.wrappers.Logger; - import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; - +import org.openecomp.sdc.common.log.wrappers.Logger; public abstract class AbstractScheduleTaskRunner { + private static final Logger log = Logger.getLogger(AbstractScheduleTaskRunner.class); + public abstract ExecutorService getExecutorService(); protected void shutdownExecutor() { ExecutorService executorService = getExecutorService(); - if (executorService == null) + 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 + + // tasks + // Wait a while for tasks to respond to being cancelled - if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) + if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { log.debug("Pool did not terminate"); + } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted 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 index e67b2e1235..64874a9fa8 100644 --- 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 @@ -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. @@ -17,9 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.scheduledtasks; +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; +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; @@ -29,43 +37,27 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.common.log.wrappers.Logger; 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 = Logger.getLogger(AsdcComponentsCleanerTask.class); - + ScheduledFuture scheduledFuture = null; @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; + private ScheduledExecutorService scheduledService = Executors + .newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build()); @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"); + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init", "fecth configuration"); return; - } componentsToClean = new ArrayList<>(); List components = cleanComponentsConfiguration.getComponentsToClean(); @@ -74,20 +66,17 @@ public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implem } for (String component : components) { NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(component); - if (typeEnum != null) - componentsToClean.add(typeEnum); + 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"); } @@ -98,22 +87,15 @@ public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implem } 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); - + scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes, TimeUnit.MINUTES); } } catch (Exception e) { log.debug("unexpected error occured", e); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask", - e.getMessage()); - + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask", e.getMessage()); } } @@ -122,12 +104,11 @@ public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implem 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"); + BeEcompErrorManager.getInstance() + .logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask", "try to stop the polling task"); } scheduledFuture = null; } - } @Override @@ -136,10 +117,8 @@ public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implem componentsCleanBusinessLogic.cleanComponents(componentsToClean); } catch (Exception e) { log.error("unexpected error occured", e); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run", - e.getMessage()); + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run", e.getMessage()); } - } @Override 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 index 8c56052dc8..f3b11e8247 100644 --- 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 @@ -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. @@ -19,11 +19,13 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.scheduledtasks; import com.google.common.annotations.VisibleForTesting; import fj.data.Either; +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; @@ -43,44 +45,32 @@ import org.openecomp.sdc.exception.ResponseFormat; 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 { - private final ResourceBusinessLogic resourceBusinessLogic; - private final ServiceBusinessLogic serviceBusinessLogic; - @VisibleForTesting static final String DELETE_LOCKER = "DELETE_LOCKER"; - private static final Logger log = Logger.getLogger(ComponentsCleanBusinessLogic.class.getName()); + private final ResourceBusinessLogic resourceBusinessLogic; + private final ServiceBusinessLogic serviceBusinessLogic; @Autowired - public ComponentsCleanBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ResourceBusinessLogic resourceBusinessLogic, - ServiceBusinessLogic serviceBusinessLogic, - ArtifactsOperations artifactToscaOperation) { - super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + public ComponentsCleanBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ResourceBusinessLogic resourceBusinessLogic, + ServiceBusinessLogic serviceBusinessLogic, ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, + artifactToscaOperation); this.resourceBusinessLogic = resourceBusinessLogic; this.serviceBusinessLogic = serviceBusinessLogic; } - public Map, ResponseFormat>> cleanComponents(List componentsToClean){ + public Map, ResponseFormat>> cleanComponents(List componentsToClean) { return cleanComponents(componentsToClean, false); } public Map, ResponseFormat>> cleanComponents(List componentsToClean, boolean isAlreadyLocked) { - Map, ResponseFormat>> cleanedComponents = new HashMap<>(); - boolean isLockSucceeded = false; log.trace("start cleanComponents"); try { @@ -106,18 +96,17 @@ public class ComponentsCleanBusinessLogic extends BaseBusinessLogic { break; } } - } - finally { + } finally { if (!isAlreadyLocked && isLockSucceeded) { unlockDeleteOperation(); } } - log.trace("end cleanComponents"); return cleanedComponents; } - private void processDeletionForType(Map, ResponseFormat>> cleanedComponents, NodeTypeEnum type, ComponentBusinessLogic componentBusinessLogic) { + 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()); @@ -142,5 +131,4 @@ public class ComponentsCleanBusinessLogic extends BaseBusinessLogic { public boolean isDeleteOperationLockFailed() { return lockDeleteOperation() != StorageOperationStatus.OK; } - } 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 index 4aa6136994..594e0b9418 100644 --- 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 @@ -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. @@ -17,11 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.scheduledtasks; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.convertToFunction; + import com.google.common.annotations.VisibleForTesting; import fj.data.Either; +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 javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine; @@ -36,45 +47,28 @@ import org.openecomp.sdc.common.log.wrappers.Logger; 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 = Logger.getLogger(RecoveryThreadManager.class); @VisibleForTesting FixEnvironmentTask task = new FixEnvironmentTask(); - + @VisibleForTesting + Integer allowedTimeBeforeStaleSec; @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; + private ScheduledExecutorService scheduledService = Executors + .newScheduledThreadPool(NumberUtils.INTEGER_ONE, new BasicThreadFactory.Builder().namingPattern("EnvironmentCleanThread-%d").build()); @PostConstruct public void init() { log.debug("Enter init method of RecoveryThreadManager"); - final DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager - .getConfigurationManager().getDistributionEngineConfiguration(); + final DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); Integer opEnvRecoveryIntervalSec = distributionEngineConfiguration.getOpEnvRecoveryIntervalSec(); - scheduledService.scheduleAtFixedRate(task, NumberUtils.INTEGER_ZERO, opEnvRecoveryIntervalSec, - TimeUnit.SECONDS); + scheduledService.scheduleAtFixedRate(task, NumberUtils.INTEGER_ZERO, opEnvRecoveryIntervalSec, TimeUnit.SECONDS); this.allowedTimeBeforeStaleSec = distributionEngineConfiguration.getAllowedTimeBeforeStaleSec(); log.debug("End init method of AsdcComponentsCleaner"); } @@ -84,29 +78,31 @@ public class RecoveryThreadManager extends AbstractScheduleTaskRunner { shutdownExecutor(); } + @Override + public ExecutorService getExecutorService() { + return scheduledService; + } + 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))); - + .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); + .getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS); eitherInProgressEnv.bimap(convertToFunction(this::handleInProgressEnvironmentsRecords), - convertToFunction(cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.IN_PROGRESS, - cassandraError))); - + 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))); - + .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); } @@ -114,49 +110,33 @@ public class RecoveryThreadManager extends AbstractScheduleTaskRunner { private void handleCompleteEnvironmentsRecords(List completeEnvironmentsRecords) { if (!isEmpty(completeEnvironmentsRecords)) { - completeEnvironmentsRecords.stream().filter(env -> !environmentsEngine.isInMap(env)) - .forEach(opEnvEntry -> { - environmentsEngine.createUebTopicsForEnvironment(opEnvEntry); - environmentsEngine.addToMap(opEnvEntry); - }); + 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)); + 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)); + .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/upgrade/ServiceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/ServiceInfo.java index 025ee589fb..080d38e178 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/ServiceInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/ServiceInfo.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. @@ -17,46 +17,54 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.upgrade; import org.openecomp.sdc.be.dao.api.ActionStatus; public class ServiceInfo { + private String uniqueId; private String version; private String name; private ActionStatus status; - - public ServiceInfo(){ + + public ServiceInfo() { status = ActionStatus.OK; } - - public ServiceInfo(String id, ActionStatus status){ + + public ServiceInfo(String id, ActionStatus status) { this.uniqueId = id; this.status = status; } + public String getUniqueId() { return uniqueId; } + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } + public String getVersion() { return version; } + public void setVersion(String version) { this.version = version; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public ActionStatus getStatus() { return status; } + public void setStatus(ActionStatus status) { this.status = status; } @@ -74,31 +82,40 @@ public class ServiceInfo { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } ServiceInfo other = (ServiceInfo) obj; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (status != other.status) - return false; + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (status != other.status) { + return false; + } if (uniqueId == null) { - if (other.uniqueId != null) - return false; - } else if (!uniqueId.equals(other.uniqueId)) - return false; + if (other.uniqueId != null) { + return false; + } + } else if (!uniqueId.equals(other.uniqueId)) { + return false; + } if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; + if (other.version != null) { + return false; + } + } else if (!version.equals(other.version)) { + return false; + } return true; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.java index dbe5141fe0..fb8c873240 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.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. @@ -17,10 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.upgrade; import fj.data.Either; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; @@ -48,16 +53,13 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - @org.springframework.stereotype.Component("upgradeBusinessLogic") public class UpgradeBusinessLogic { + private static final List UUID_PROPS_NAMES = Arrays.asList("depending_service_uuid", "providing_service_uuid"); + private static final List INV_UUID_PROPS_NAMES = Arrays.asList("depending_service_invariant_uuid", "providing_service_invariant_uuid"); + private static final List NAME_PROPS_NAMES = Arrays.asList("depending_service_name", "providing_service_name"); + private static final Logger LOGGER = Logger.getLogger(UpgradeBusinessLogic.class); private final LifecycleBusinessLogic lifecycleBusinessLogic; private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; private final UserValidations userValidations; @@ -67,13 +69,8 @@ public class UpgradeBusinessLogic { private final JanusGraphDao janusGraphDao; private LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("automated upgrade"); - private static final List UUID_PROPS_NAMES = Arrays.asList("depending_service_uuid", "providing_service_uuid"); - private static final List INV_UUID_PROPS_NAMES = Arrays.asList("depending_service_invariant_uuid", "providing_service_invariant_uuid"); - private static final List NAME_PROPS_NAMES = Arrays.asList("depending_service_name", "providing_service_name"); - - private static final Logger LOGGER = Logger.getLogger(UpgradeBusinessLogic.class); - - public UpgradeBusinessLogic(LifecycleBusinessLogic lifecycleBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, UserValidations userValidations, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, + public UpgradeBusinessLogic(LifecycleBusinessLogic lifecycleBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, + UserValidations userValidations, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, UpgradeOperation upgradeOperation, JanusGraphDao janusGraphDao) { this.lifecycleBusinessLogic = lifecycleBusinessLogic; this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; @@ -84,9 +81,7 @@ public class UpgradeBusinessLogic { this.janusGraphDao = janusGraphDao; } - /** - * * @param componentId * @param userId * @return @@ -94,61 +89,56 @@ public class UpgradeBusinessLogic { public UpgradeStatus automatedUpgrade(String componentId, List upgradeRequest, String userId) { UpgradeStatus status = new UpgradeStatus(); User user = userValidations.validateUserExists(userId); - Either storageStatus = toscaOperationFacade.getToscaFullElement(componentId); if (storageStatus.isRight()) { - status.setError(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), componentId)); + status.setError( + componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), componentId)); return status; } Component component = storageStatus.left().value(); if (!component.isHighestVersion() || component.getLifecycleState() != LifecycleStateEnum.CERTIFIED) { - LOGGER.debug("automated Upgrade failed - target is not higest certified component {} state {} version {} ", component.getName(), component.getLifecycleState(), component.getVersion()); + LOGGER.debug("automated Upgrade failed - target is not higest certified component {} state {} version {} ", component.getName(), + component.getLifecycleState(), component.getVersion()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_NOT_HIHGEST_CERTIFIED, component.getName()); status.setError(responseFormat); componentsUtils.auditComponentAdmin(responseFormat, user, component, getAuditTypeByComponent(component), component.getComponentType()); - return status; } - if ( component.isArchived() ){ + if (component.isArchived()) { LOGGER.debug("automated Upgrade failed - target is archived component {} version {} ", component.getName(), component.getVersion()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, component.getName()); status.setError(responseFormat); componentsUtils.auditComponentAdmin(responseFormat, user, component, getAuditTypeByComponent(component), component.getComponentType()); - return status; } switch (component.getComponentType()) { - case RESOURCE: - hadnleUpgradeVFInService(component, upgradeRequest, user, status); - break; - case SERVICE: - hadnleUpgradeService(component, upgradeRequest, user, status); - break; - default: - LOGGER.debug("automated Upgrade failed - Not supported type {} for component {} ", component.getComponentType(), component.getName()); - status.setError(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR)); + case RESOURCE: + hadnleUpgradeVFInService(component, upgradeRequest, user, status); + break; + case SERVICE: + hadnleUpgradeService(component, upgradeRequest, user, status); + break; + default: + LOGGER.debug("automated Upgrade failed - Not supported type {} for component {} ", component.getComponentType(), component.getName()); + status.setError(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR)); } return status; } /** - * * @param componentId * @param userId * @return */ public Either, ResponseFormat> getComponentDependencies(String componentId, String userId) { - User user = userValidations.validateUserExists(userId); try { - return upgradeOperation.getComponentDependencies(componentId) - .right() - .map(rf -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(rf))); + return upgradeOperation.getComponentDependencies(componentId).right() + .map(rf -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(rf))); } finally { // all operation were read only. no commit needed janusGraphDao.rollback(); } - } private UpgradeStatus hadnleUpgradeVFInService(Component component, List componentUids, User user, UpgradeStatus upgradeStatus) { @@ -156,26 +146,30 @@ public class UpgradeBusinessLogic { if (vfResource.getResourceType() != ResourceTypeEnum.VF) { LOGGER.debug("automated Upgrade failed - target is not VF resource {} {} ", vfResource.getName(), vfResource.getResourceType()); upgradeStatus.setStatus(ActionStatus.GENERAL_ERROR); - componentsUtils.auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR), user, component, getAuditTypeByComponent(component), component.getComponentType()); + componentsUtils.auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR), user, component, + getAuditTypeByComponent(component), component.getComponentType()); return upgradeStatus; } componentUids.forEach(request -> upgradeInSingleService(request, vfResource, user, upgradeStatus)); upgradeStatus.setStatus(ActionStatus.OK); - componentsUtils.auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.VF_UPGRADE_SERVICES, component.getComponentType()); - + componentsUtils + .auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.VF_UPGRADE_SERVICES, + component.getComponentType()); return upgradeStatus; } private UpgradeStatus hadnleUpgradeService(Component component, List upgradeRequest, User user, UpgradeStatus upgradeStatus) { - if ( Role.TESTER.name().equals(user.getRole()) ){ + if (Role.TESTER.name().equals(user.getRole())) { user.setRole(Role.DESIGNER.name()); LOGGER.debug("Change temporary for update service reference user role from TESTER to DESINGER"); } Service service = (Service) component; upgradeRequest.forEach(request -> upgradeSingleService(request, service, user, upgradeStatus)); upgradeStatus.setStatus(ActionStatus.OK); - componentsUtils.auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.UPDATE_SERVICE_REFERENCE, component.getComponentType()); - return upgradeStatus; + componentsUtils + .auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.UPDATE_SERVICE_REFERENCE, + component.getComponentType()); + return upgradeStatus; } private ActionStatus upgradeSingleService(UpgradeRequest request, Service service, User user, UpgradeStatus upgradeStatus) { @@ -190,8 +184,7 @@ public class UpgradeBusinessLogic { private ActionStatus upgradeInSingleService(UpgradeRequest request, Component newVersionComponent, User user, UpgradeStatus upgradeStatus) { String serviceId = request.getServiceId(); - return toscaOperationFacade.getToscaFullElement(serviceId) - .either(l -> handleService(l, newVersionComponent, user, upgradeStatus), err -> { + return toscaOperationFacade.getToscaFullElement(serviceId).either(l -> handleService(l, newVersionComponent, user, upgradeStatus), err -> { LOGGER.debug("Failed to fetch service by id {} error {}", serviceId, err); ActionStatus errS = componentsUtils.convertFromStorageResponse(err); upgradeStatus.addServiceStatus(serviceId, errS); @@ -205,10 +198,8 @@ public class UpgradeBusinessLogic { if (upgradeAllottedResource.isRight()) { return upgradeAllottedResource.right().value(); } - resource = upgradeAllottedResource.left().value(); // update VF instance in service - Either serviceContainer = toscaOperationFacade.getToscaFullElement(request.getServiceId()); if (serviceContainer.isRight()) { LOGGER.debug("Failed to fetch resource by id {} error {}", request.getServiceId(), serviceContainer.right().value()); @@ -217,82 +208,84 @@ public class UpgradeBusinessLogic { return errS; } return handleService(serviceContainer.left().value(), resource, user, upgradeStatus); - } - private Either upgradeAllottedResource(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, Service service) { - return getElement(request.getResourceId(), upgradeStatus, request) - .left() - .bind(l -> upgradeStateAlloted(request, user, upgradeStatus, service, l)); + private Either upgradeAllottedResource(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, + Service service) { + return getElement(request.getResourceId(), upgradeStatus, request).left() + .bind(l -> upgradeStateAlloted(request, user, upgradeStatus, service, l)); } private Either getElement(String id, UpgradeStatus upgradeStatus, UpgradeRequest request) { - return toscaOperationFacade.getToscaElement(id) - .right() - .map(err -> { + return toscaOperationFacade.getToscaElement(id).right().map(err -> { ActionStatus errS = componentsUtils.convertFromStorageResponse(err); upgradeStatus.addServiceStatus(request.getServiceId(), errS); return errS; }); } - private Either upgradeStateAlloted(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, Service service, Component resource) { + private Either upgradeStateAlloted(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, + Service service, Component resource) { if (resource.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { LOGGER.debug("Automated upgrade failedd. Alloted vf {} is in state NOT_CERTIFIED_CHECKOUT", request.getResourceId()); upgradeStatus.addServiceStatus(request.getServiceId(), ActionStatus.RESOURCE_LIFECYCLE_STATE_NOT_VALID); return Either.right(ActionStatus.RESOURCE_LIFECYCLE_STATE_NOT_VALID); } // check out VF + // update properties-reference to service in VF on VFCI - return changeComponentState(resource, LifeCycleTransitionEnum.CHECKOUT, user, upgradeStatus, request.getServiceId()) - .left() - .bind(l -> updateAllottedPropsAndCertify(request, user, upgradeStatus, service, l)); + return changeComponentState(resource, LifeCycleTransitionEnum.CHECKOUT, user, upgradeStatus, request.getServiceId()).left() + .bind(l -> updateAllottedPropsAndCertify(request, user, upgradeStatus, service, l)); } - private Either updateAllottedPropsAndCertify(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, Service service, Component resource) { + private Either updateAllottedPropsAndCertify(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, + Service service, Component resource) { Either result = null; try { List instanceIds = upgradeOperation.getInstanceIdFromAllottedEdge(resource.getUniqueId(), service.getInvariantUUID()); if (instanceIds != null) { Map> componentInstancesProperties = resource.getComponentInstancesProperties(); Map> propertiesToUpdate = new HashMap<>(); - instanceIds.forEach(id -> findPropertiesToUpdate(id, componentInstancesProperties, propertiesToUpdate, service)); - - Either>, StorageOperationStatus> updatePropsResult = toscaOperationFacade.updateComponentInstancePropsToComponent(propertiesToUpdate, resource.getUniqueId()); + Either>, StorageOperationStatus> updatePropsResult = toscaOperationFacade + .updateComponentInstancePropsToComponent(propertiesToUpdate, resource.getUniqueId()); if (updatePropsResult.isRight()) { - LOGGER.debug("Failed to update properties in Allotted resource {} {}, Error {}. ", resource.getName(), resource.getUniqueId(), updatePropsResult.right().value()); - + LOGGER.debug("Failed to update properties in Allotted resource {} {}, Error {}. ", resource.getName(), resource.getUniqueId(), + updatePropsResult.right().value()); result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - // certify VF - result = changeComponentState(resource, LifeCycleTransitionEnum.CERTIFY, user, upgradeStatus, request.getServiceId()); + result = changeComponentState(resource, LifeCycleTransitionEnum.CERTIFY, user, upgradeStatus, request.getServiceId()); } else { // nothing to update LOGGER.debug("No Instances to update in allotted resource {} ", resource.getName()); result = Either.right(ActionStatus.NO_INSTANCES_TO_UPGRADE); } return result; - } finally { - if ( result != null && result.isRight() ){ + } finally { + if (result != null && result.isRight()) { // undo checkout resource in case of failure - LOGGER.debug("Failed to update Allotted resource {} {}, Error {}. UNDOCHEKOUT our resource", resource.getName(), resource.getUniqueId(), result.right().value()); - + LOGGER + .debug("Failed to update Allotted resource {} {}, Error {}. UNDOCHEKOUT our resource", resource.getName(), resource.getUniqueId(), + result.right().value()); upgradeStatus.addServiceStatus(request.getServiceId(), ActionStatus.GENERAL_ERROR); } } } private void undocheckoutComponent(User user, Component resource) { - Either changeComponentState = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.UNDO_CHECKOUT, changeInfo, false, true); + Either changeComponentState = lifecycleBusinessLogic + .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.UNDO_CHECKOUT, changeInfo, false, + true); if (changeComponentState.isRight()) { - LOGGER.debug("Failed to UNDOCHECKOUT Service {} {}, Error {}", resource.getName(), resource.getUniqueId(), changeComponentState.right().value()); + LOGGER.debug("Failed to UNDOCHECKOUT Service {} {}, Error {}", resource.getName(), resource.getUniqueId(), + changeComponentState.right().value()); } } - private void findPropertiesToUpdate(String id, Map> componentInstancesProperties, Map> propertiesToUpdate, Service service) { + private void findPropertiesToUpdate(String id, Map> componentInstancesProperties, + Map> propertiesToUpdate, Service service) { List list = componentInstancesProperties.get(id); List propsPerInstance = new ArrayList<>(); list.forEach(p -> { @@ -314,29 +307,30 @@ public class UpgradeBusinessLogic { private ActionStatus handleService(Component component, Component newVersionComponent, User user, UpgradeStatus upgradeStatus) { if (component.getComponentType() != ComponentTypeEnum.SERVICE) { - LOGGER.debug("component with id {} and name {} isn't SERVICE. type{} ", component.getName(), component.getUniqueId(), component.getComponentType()); + LOGGER.debug("component with id {} and name {} isn't SERVICE. type{} ", component.getName(), component.getUniqueId(), + component.getComponentType()); upgradeStatus.addServiceStatus(component, ActionStatus.GENERAL_ERROR); return ActionStatus.GENERAL_ERROR; } - Service service = (Service) component; if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { LOGGER.debug("Service {} {} is not in CHECKOUT state . Try to checkout it", component.getName(), component.getUniqueId()); - Either changeComponentState = changeComponentState(component, LifeCycleTransitionEnum.CHECKOUT, user, upgradeStatus, null); - if ( changeComponentState.isRight() ){ + Either changeComponentState = changeComponentState(component, LifeCycleTransitionEnum.CHECKOUT, user, + upgradeStatus, null); + if (changeComponentState.isRight()) { return changeComponentState.right().value(); } service = (Service) changeComponentState.left().value(); //need to fetch service again with capability properties Either toscaFullElement = toscaOperationFacade.getToscaFullElement(service.getUniqueId()); - if ( toscaFullElement.isRight() ){ + if (toscaFullElement.isRight()) { return componentsUtils.convertFromStorageResponse(toscaFullElement.right().value()); } service = (Service) toscaFullElement.left().value(); - }else{ + } else { LOGGER.debug("Service {} {} is in CHECKOUT state . Restricted update operation", component.getName(), component.getUniqueId()); upgradeStatus.addServiceStatus(component, ActionStatus.COMPONENT_IN_CHECKOUT_STATE); - return ActionStatus.COMPONENT_IN_CHECKOUT_STATE; + return ActionStatus.COMPONENT_IN_CHECKOUT_STATE; } ActionStatus status = ActionStatus.GENERAL_ERROR; try { @@ -345,34 +339,34 @@ public class UpgradeBusinessLogic { if (status != ActionStatus.OK) { LOGGER.debug("Failed to upgrade instance for service {} status {}. Undocheckout service", service.getName(), status); undocheckoutComponent(user, service); - upgradeStatus.addServiceStatus(component, status); } } return status; } - - private Either changeComponentState(Component component, LifeCycleTransitionEnum nextState, User user, UpgradeStatus upgradeStatus, String idForStatus){ - if ( component.isArchived() ){ - LOGGER.debug("Component {} from type {} id {} is archived, Error {}", nextState, component.getName(), component.getComponentType(), component.getUniqueId()); + + private Either changeComponentState(Component component, LifeCycleTransitionEnum nextState, User user, + UpgradeStatus upgradeStatus, String idForStatus) { + if (component.isArchived()) { + LOGGER.debug("Component {} from type {} id {} is archived, Error {}", nextState, component.getName(), component.getComponentType(), + component.getUniqueId()); setUpgradeStatus(component, upgradeStatus, idForStatus); return Either.right(ActionStatus.COMPONENT_IS_ARCHIVED); } - return lifecycleBusinessLogic.changeComponentState(component.getComponentType(), component.getUniqueId(), user, nextState, changeInfo, false, true) - .right() - .map(err-> { - LOGGER.debug("Failed to {} Component {} from type {} id {}, Error {}", nextState, component.getName(), component.getComponentType(), component.getUniqueId(), err); - setUpgradeStatus(component, upgradeStatus, idForStatus); - return ActionStatus.GENERAL_ERROR; - - }); + return lifecycleBusinessLogic + .changeComponentState(component.getComponentType(), component.getUniqueId(), user, nextState, changeInfo, false, true).right() + .map(err -> { + LOGGER.debug("Failed to {} Component {} from type {} id {}, Error {}", nextState, component.getName(), component.getComponentType(), + component.getUniqueId(), err); + setUpgradeStatus(component, upgradeStatus, idForStatus); + return ActionStatus.GENERAL_ERROR; + }); } - private void setUpgradeStatus(Component component, UpgradeStatus upgradeStatus, String idForStatus) { - if ( idForStatus == null ){ + if (idForStatus == null) { upgradeStatus.addServiceStatus(component, ActionStatus.GENERAL_ERROR); - }else{ + } else { upgradeStatus.addServiceStatus(idForStatus, ActionStatus.GENERAL_ERROR); } } @@ -380,10 +374,8 @@ public class UpgradeBusinessLogic { private ActionStatus handleInstances(Component newVersionComponent, User user, UpgradeStatus upgradeStatus, Service service) { List componentInstances = service.getComponentInstances(); if (componentInstances != null) { - List instanceToChange = componentInstances - .stream() - .filter(ci -> matchInstance(ci, newVersionComponent)) - .collect(Collectors.toList()); + List instanceToChange = componentInstances.stream().filter(ci -> matchInstance(ci, newVersionComponent)) + .collect(Collectors.toList()); if (instanceToChange != null && !instanceToChange.isEmpty()) { return changeInstances(newVersionComponent, user, upgradeStatus, service, instanceToChange); } else { @@ -394,11 +386,12 @@ public class UpgradeBusinessLogic { return ActionStatus.OK; } - private ActionStatus changeInstances(Component newVersionComponent, User user, UpgradeStatus upgradeStatus, Service service, List instanceToChange) { + private ActionStatus changeInstances(Component newVersionComponent, User user, UpgradeStatus upgradeStatus, Service service, + List instanceToChange) { Component serviceToUpgrade = service; for (ComponentInstance ci : instanceToChange) { - Either fetchService = fetchService(service.getUniqueId(),service.getName()); - if ( fetchService.isRight()){ + Either fetchService = fetchService(service.getUniqueId(), service.getName()); + if (fetchService.isRight()) { upgradeStatus.addServiceStatus(service, fetchService.right().value()); return fetchService.right().value(); } @@ -410,36 +403,34 @@ public class UpgradeBusinessLogic { return status; } } - Either fetchService = fetchService(service.getUniqueId(),service.getName()); - if ( fetchService.isRight()){ + Either fetchService = fetchService(service.getUniqueId(), service.getName()); + if (fetchService.isRight()) { upgradeStatus.addServiceStatus(service, fetchService.right().value()); return fetchService.right().value(); } serviceToUpgrade = fetchService.left().value(); - - Either changeComponentState = changeComponentState(serviceToUpgrade, LifeCycleTransitionEnum.CHECKIN, user, upgradeStatus, null); - if ( changeComponentState.isRight() ){ + Either changeComponentState = changeComponentState(serviceToUpgrade, LifeCycleTransitionEnum.CHECKIN, user, + upgradeStatus, null); + if (changeComponentState.isRight()) { return changeComponentState.right().value(); } upgradeStatus.addServiceStatus(serviceToUpgrade, ActionStatus.OK); return ActionStatus.OK; } - private Either fetchService(String uniqueId, String name) { - return toscaOperationFacade.getToscaFullElement(uniqueId) - .right() - .map(r->{ - LOGGER.debug("Failed to fetch service {} id {} error {}", name, uniqueId, r); - return ActionStatus.GENERAL_ERROR; - }); + return toscaOperationFacade.getToscaFullElement(uniqueId).right().map(r -> { + LOGGER.debug("Failed to fetch service {} id {} error {}", name, uniqueId, r); + return ActionStatus.GENERAL_ERROR; + }); } private ActionStatus changeVersionOfInstance(Component service, ComponentInstance ci, Component newVersionComponent, User user) { LOGGER.debug("In Service {} change instance version {} to version {}", service.getName(), ci.getName(), newVersionComponent.getVersion()); ComponentInstance newComponentInstance = new ComponentInstance(); newComponentInstance.setComponentUid(newVersionComponent.getUniqueId()); - ComponentInstance changeInstanceVersion = componentInstanceBusinessLogic.changeInstanceVersion(service, ci, newComponentInstance, user, service.getComponentType()); + ComponentInstance changeInstanceVersion = componentInstanceBusinessLogic + .changeInstanceVersion(service, ci, newComponentInstance, user, service.getComponentType()); return ActionStatus.OK; } @@ -457,18 +448,19 @@ public class UpgradeBusinessLogic { } if (toscaElement.isLeft()) { Component origin = toscaElement.left().value(); - if (newVersionComponent.getInvariantUUID().equals(origin.getInvariantUUID()) && !newVersionComponent.getVersion().equals(origin.getVersion())) { + if (newVersionComponent.getInvariantUUID().equals(origin.getInvariantUUID()) && !newVersionComponent.getVersion() + .equals(origin.getVersion())) { // only for same invariant UUID (same component) but different versions return true; } } return false; } - private AuditingActionEnum getAuditTypeByComponent(Component component){ - if ( ComponentTypeEnum.RESOURCE == component.getComponentType()){ + + private AuditingActionEnum getAuditTypeByComponent(Component component) { + if (ComponentTypeEnum.RESOURCE == component.getComponentType()) { return AuditingActionEnum.VF_UPGRADE_SERVICES; } return AuditingActionEnum.UPDATE_SERVICE_REFERENCE; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeRequest.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeRequest.java index d4324592c9..d84c32be43 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeRequest.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeRequest.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. @@ -17,36 +17,38 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.upgrade; public class UpgradeRequest { + private String serviceId; private String resourceId; - - public UpgradeRequest(){ - + + public UpgradeRequest() { } - public UpgradeRequest(String serviceId ){ + + public UpgradeRequest(String serviceId) { this.serviceId = serviceId; } - public UpgradeRequest(String serviceId, String resourceId ){ + + public UpgradeRequest(String serviceId, String resourceId) { this.serviceId = serviceId; this.resourceId = resourceId; } - + public String getServiceId() { return serviceId; } + public void setServiceId(String serviceId) { this.serviceId = serviceId; } + public String getResourceId() { return resourceId; } + public void setResourceId(String resourceId) { this.resourceId = resourceId; } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeStatus.java index da4dd6b163..46d7307c80 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeStatus.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeStatus.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. @@ -17,21 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.upgrade; +import java.util.ArrayList; +import java.util.List; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.ArrayList; -import java.util.List; - public class UpgradeStatus { + ActionStatus status; ResponseFormat error; - - List componentToUpgradeStatus; public ActionStatus getStatus() { @@ -54,14 +51,16 @@ public class UpgradeStatus { checkAndCreate(); componentToUpgradeStatus.add(info); } + public void addServiceStatus(String serviceId, ActionStatus status) { checkAndCreate(); - ServiceInfo info = new ServiceInfo(serviceId, status ); + ServiceInfo info = new ServiceInfo(serviceId, status); componentToUpgradeStatus.add(info); } + public void addServiceStatus(Component component, ActionStatus status) { checkAndCreate(); - ServiceInfo info = new ServiceInfo(component.getUniqueId(), status ); + ServiceInfo info = new ServiceInfo(component.getUniqueId(), status); info.setName(component.getName()); info.setVersion(component.getVersion()); componentToUpgradeStatus.add(info); @@ -80,5 +79,4 @@ public class UpgradeStatus { public void setError(ResponseFormat error) { this.error = error; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ArtifactUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ArtifactUtils.java index 9f95caa2fa..ffe1d406a8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ArtifactUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ArtifactUtils.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.utils; import com.google.gson.Gson; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ConsumptionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ConsumptionUtils.java index d6e881dba0..c4eaa3accd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ConsumptionUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ConsumptionUtils.java @@ -13,11 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.utils; import com.google.gson.Gson; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -28,37 +33,27 @@ import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; import org.openecomp.sdc.be.types.ServiceConsumptionData; import org.openecomp.sdc.exception.ResponseFormat; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; public class ConsumptionUtils { private ConsumptionUtils() { - } - public static Either handleConsumptionInputMappedToCapabilityProperty( - Operation operation, - OperationInputDefinition operationInputDefinition, ServiceConsumptionData serviceConsumptionData, - Map> capabilities, String componentName) { - - List componentCapabilityDefinitions = capabilities.values().stream() - .flatMap(Collection::stream) - .collect(Collectors.toList()); + public static Either handleConsumptionInputMappedToCapabilityProperty(Operation operation, + OperationInputDefinition operationInputDefinition, + ServiceConsumptionData serviceConsumptionData, + Map> capabilities, + String componentName) { + List componentCapabilityDefinitions = capabilities.values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); if (CollectionUtils.isEmpty(componentCapabilityDefinitions)) { return Either.left(operation); } - for (CapabilityDefinition capabilityDefinition : componentCapabilityDefinitions) { String capabilityName = capabilityDefinition.getName(); List capabilityProperties = capabilityDefinition.getProperties(); @@ -69,14 +64,12 @@ public class ConsumptionUtils { String capabilityPropertyName = capabilityProperty.getName(); String capabilityPropertyIdentifier = capabilityName + "_" + capabilityPropertyName; if (capabilityPropertyIdentifier.equals(serviceConsumptionData.getValue())) { - boolean isInputTypeSimilarToOperation = - isAssignedValueFromValidType(operationInputDefinition.getType(), capabilityProperty); + boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), capabilityProperty); if (!isInputTypeSimilarToOperation) { - return Either.right(getResponseFormatManager().getResponseFormat( - ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType())); + return Either.right( + getResponseFormatManager().getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType())); } - addCapabilityPropertyToInputValue(componentName, capabilityName, operation, - operationInputDefinition, capabilityProperty); + addCapabilityPropertyToInputValue(componentName, capabilityName, operation, operationInputDefinition, capabilityProperty); } } } @@ -84,21 +77,16 @@ public class ConsumptionUtils { } private static void addCapabilityPropertyToInputValue(String componentName, String capabilityName, Operation operation, - OperationInputDefinition operationInputDefinition, - PropertyDefinition capabilityProperty) { - + OperationInputDefinition operationInputDefinition, PropertyDefinition capabilityProperty) { List getPropertyValues = new ArrayList<>(); getPropertyValues.add(componentName); getPropertyValues.add(capabilityName); getPropertyValues.add(capabilityProperty.getName()); - Map> getProperty = new HashMap<>(); getProperty.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), getPropertyValues); - operationInputDefinition.setSourceProperty(capabilityProperty.getUniqueId()); operation.getInputs().delete(operationInputDefinition); - operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY, - getPropertyValues); + operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY, getPropertyValues); operationInputDefinition.setValue((new Gson()).toJson(getProperty)); operation.getInputs().add(operationInputDefinition); } @@ -108,7 +96,7 @@ public class ConsumptionUtils { // validate static value ToscaPropertyType actualType = ToscaPropertyType.isValidType(operationInputType); PropertyTypeValidator validator = actualType.getValidator(); - return validator.isValid((String)actualValue, operationInputType); + return validator.isValid((String) actualValue, operationInputType); } else if (actualValue instanceof PropertyDefinition) { // validate input / property value String actualType = ((PropertyDefinition) actualValue).getType(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java index 17c4b04d0f..edbad79e14 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java @@ -13,9 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.utils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; @@ -27,90 +34,63 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.be.tosca.InterfacesOperationsConverter; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; public class InterfaceOperationUtils { private InterfaceOperationUtils() { } - public static Optional getInterfaceDefinitionFromComponentByInterfaceType(Component component, - String interfaceType) { + public static Optional getInterfaceDefinitionFromComponentByInterfaceType(Component component, String interfaceType) { if (MapUtils.isEmpty(component.getInterfaces())) { return Optional.empty(); } return component.getInterfaces().values().stream() - .filter(interfaceDefinition -> interfaceDefinition.getType() != null && interfaceDefinition - .getType() - .equals(interfaceType)) - .findAny(); + .filter(interfaceDefinition -> interfaceDefinition.getType() != null && interfaceDefinition.getType().equals(interfaceType)).findAny(); } - public static Optional getInterfaceDefinitionFromComponentByInterfaceId(Component component, - String interfaceId) { + public static Optional getInterfaceDefinitionFromComponentByInterfaceId(Component component, String interfaceId) { if (MapUtils.isEmpty(component.getInterfaces())) { return Optional.empty(); } return component.getInterfaces().values().stream() - .filter(interfaceDefinition -> interfaceDefinition.getUniqueId() != null && interfaceDefinition - .getUniqueId() - .equals(interfaceId)) - .findAny(); + .filter(interfaceDefinition -> interfaceDefinition.getUniqueId() != null && interfaceDefinition.getUniqueId().equals(interfaceId)) + .findAny(); } - public static Optional> getOperationFromInterfaceDefinition( - InterfaceDefinition interfaceDefinition, String operationId) { + public static Optional> getOperationFromInterfaceDefinition(InterfaceDefinition interfaceDefinition, + String operationId) { if (MapUtils.isEmpty(interfaceDefinition.getOperationsMap())) { return Optional.empty(); } - return interfaceDefinition.getOperationsMap().entrySet().stream() - .filter(entry -> entry.getValue().getUniqueId().equals(operationId)).findAny(); + return interfaceDefinition.getOperationsMap().entrySet().stream().filter(entry -> entry.getValue().getUniqueId().equals(operationId)) + .findAny(); } - public static Optional getInterfaceDefinitionFromOperationId(List interfaces, - String operationId) { + public static Optional getInterfaceDefinitionFromOperationId(List interfaces, String operationId) { if (CollectionUtils.isEmpty(interfaces)) { return Optional.empty(); } - return interfaces.stream() - .filter(interfaceDefinition -> interfaceDefinition.getOperationsMap().containsKey(operationId)) - .findAny(); + return interfaces.stream().filter(interfaceDefinition -> interfaceDefinition.getOperationsMap().containsKey(operationId)).findAny(); } - public static boolean isOperationInputMappedToComponentInput(OperationInputDefinition input, - List inputs) { + public static boolean isOperationInputMappedToComponentInput(OperationInputDefinition input, List inputs) { if (CollectionUtils.isEmpty(inputs)) { return false; } - boolean matchedInput = inputs.stream().anyMatch(inp -> inp.getUniqueId().equals(input.getInputId())); if (!matchedInput && input.getInputId().contains(".")) { - return inputs.stream() - .anyMatch(inp -> inp.getUniqueId() - .equals(input.getInputId().substring(0, input.getInputId().lastIndexOf('.')))); + return inputs.stream().anyMatch(inp -> inp.getUniqueId().equals(input.getInputId().substring(0, input.getInputId().lastIndexOf('.')))); } return matchedInput; } - public static boolean isOperationInputMappedToOtherOperationOutput(String outputName, - List - otherOperationOutputs) { + public static boolean isOperationInputMappedToOtherOperationOutput(String outputName, List otherOperationOutputs) { if (CollectionUtils.isEmpty(otherOperationOutputs)) { return false; } - return otherOperationOutputs.stream() - .anyMatch(output -> output.getName().equals(outputName)); - + return otherOperationOutputs.stream().anyMatch(output -> output.getName().equals(outputName)); } public static Map> createMappedInputPropertyDefaultValue(String propertyName) { @@ -124,13 +104,11 @@ public class InterfaceOperationUtils { return getPropertyMap; } - public static Map> createMappedCapabilityPropertyDefaultValue(String capabilityName, - String propertyName) { + public static Map> createMappedCapabilityPropertyDefaultValue(String capabilityName, String propertyName) { Map> getPropertyMap = new HashMap<>(); List values = new ArrayList<>(); values.add(InterfacesOperationsConverter.SELF); values.add(capabilityName); - if (Objects.nonNull(propertyName) && !propertyName.isEmpty()) { values.addAll(Arrays.asList(propertyName.split("\\."))); } @@ -140,18 +118,17 @@ public class InterfaceOperationUtils { /** * Get the list of outputs of other operations of all the interfaces in the component. + * * @param currentOperationIdentifier Fully qualified operation name e.g. org.test.interfaces.node.lifecycle.Abc.stop - * @param componentInterfaces VF or service interfaces + * @param componentInterfaces VF or service interfaces */ - - public static ListDataDefinition getOtherOperationOutputsOfComponent( - String currentOperationIdentifier, Map componentInterfaces) { + public static ListDataDefinition getOtherOperationOutputsOfComponent(String currentOperationIdentifier, + Map componentInterfaces) { ListDataDefinition componentOutputs = new ListDataDefinition<>(); if (MapUtils.isEmpty(componentInterfaces)) { return componentOutputs; } - for (Map.Entry interfaceDefinitionEntry : - componentInterfaces.entrySet()) { + for (Map.Entry interfaceDefinitionEntry : componentInterfaces.entrySet()) { String interfaceName = interfaceDefinitionEntry.getKey(); final Map operations = interfaceDefinitionEntry.getValue().getOperations(); if (MapUtils.isEmpty(operations)) { @@ -170,13 +147,16 @@ public class InterfaceOperationUtils { /** * Create the value for operation input mapped to an operation output. + * * @param propertyName the mapped other operation output full name * @return input map for tosca */ public static Map> createMappedOutputDefaultValue(String componentName, String propertyName) { Map> getOperationOutputMap = new HashMap<>(); //For operation input mapped to other operation output parameter, the mapped property value + // should be of the format .. + // Operation name and output param name should not contain "." List defaultMappedOperationOutputValue = new ArrayList<>(); String[] tokens = propertyName.split("\\."); @@ -184,26 +164,21 @@ public class InterfaceOperationUtils { defaultMappedOperationOutputValue.add(componentName); String outputPropertyName = tokens[tokens.length - 1]; String operationName = tokens[tokens.length - 2]; - String mappedPropertyInterfaceType = - propertyName.substring(0, propertyName.indexOf(operationName + '.' + outputPropertyName) - 1); - defaultMappedOperationOutputValue.addAll(Arrays.asList(mappedPropertyInterfaceType, operationName, - outputPropertyName)); - getOperationOutputMap.put(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName(), - defaultMappedOperationOutputValue); + String mappedPropertyInterfaceType = propertyName.substring(0, propertyName.indexOf(operationName + '.' + outputPropertyName) - 1); + defaultMappedOperationOutputValue.addAll(Arrays.asList(mappedPropertyInterfaceType, operationName, outputPropertyName)); + getOperationOutputMap.put(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName(), defaultMappedOperationOutputValue); } return getOperationOutputMap; } public static String getOperationOutputName(String fullOutputIdentifier) { - return fullOutputIdentifier.contains(".") - ? fullOutputIdentifier.substring(fullOutputIdentifier.lastIndexOf('.') + 1) - : fullOutputIdentifier; + return fullOutputIdentifier.contains(".") ? fullOutputIdentifier.substring(fullOutputIdentifier.lastIndexOf('.') + 1) : fullOutputIdentifier; } public static boolean isArtifactInUse(Component component, String operationId, String artifactUniqueId) { return MapUtils.emptyIfNull(component.getInterfaces()).values().stream() - .filter(o -> MapUtils.isNotEmpty(o.getOperations()) && !o.getOperations().containsKey(operationId)) - .flatMap(o -> o.getOperations().values().stream()).collect(Collectors.toList()).stream() - .anyMatch(op -> op.getImplementation().getUniqueId().equals(artifactUniqueId)); + .filter(o -> MapUtils.isNotEmpty(o.getOperations()) && !o.getOperations().containsKey(operationId)) + .flatMap(o -> o.getOperations().values().stream()).collect(Collectors.toList()).stream() + .anyMatch(op -> op.getImplementation().getUniqueId().equals(artifactUniqueId)); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/MapUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/MapUtils.java index bf287903f0..045658d973 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/MapUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/MapUtils.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. @@ -17,88 +17,78 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.utils; import java.util.List; import java.util.Map; public class MapUtils { - public static boolean compareMaps(Map source, Map target) { - if (source == null && target == null) { - return true; - } - if ((source == null && target != null) || source != null && target == null - || source.keySet().size() != target.keySet().size()) { - return false; - } - - for (Map.Entry entry : source.entrySet()) { - Object sourceObj = entry.getValue(); - Object targetObj = target.get(entry.getKey()); - if ((sourceObj == null && targetObj != null) || (sourceObj != null && targetObj == null)) { - return false; - } - if (!handleSourceAndTargetObjects(sourceObj, targetObj)) { - return false; - } - } - return true; - - } - - public static boolean compareLists(List source, List target) { - if (source == null && target == null) { - return true; - } - if ((source == null && target != null) || source != null && target == null || - source.size() != target.size()) { - return false; - } - for (int i = 0; i < source.size(); i++) { - Object sourceObj = source.get(i); - Object targetObj = target.get(i); - if ((sourceObj == null && targetObj != null) || sourceObj != null && targetObj == null) { - return false; - } - if (!handleSourceAndTargetObjects(sourceObj, targetObj)) { - return false; - } - } - return true; - } - - public static boolean handleSourceAndTargetObjects(Object sourceObj, Object targetObj) { - if (sourceObj == null && targetObj == null) { - return true; + public static boolean compareMaps(Map source, Map target) { + if (source == null && target == null) { + return true; + } + if ((source == null && target != null) || source != null && target == null || source.keySet().size() != target.keySet().size()) { + return false; + } + for (Map.Entry entry : source.entrySet()) { + Object sourceObj = entry.getValue(); + Object targetObj = target.get(entry.getKey()); + if ((sourceObj == null && targetObj != null) || (sourceObj != null && targetObj == null)) { + return false; + } + if (!handleSourceAndTargetObjects(sourceObj, targetObj)) { + return false; + } + } + return true; } - if (sourceObj == null && targetObj != null) { - return false; - } - if (sourceObj.getClass().equals(targetObj.getClass())) { - if (sourceObj instanceof Map) { - if (!compareMaps((Map) sourceObj, (Map) targetObj)) { - return false; + public static boolean compareLists(List source, List target) { + if (source == null && target == null) { + return true; } - } else if (sourceObj instanceof List) { - if (!compareLists((List) sourceObj, (List) targetObj)) { - return false; + if ((source == null && target != null) || source != null && target == null || source.size() != target.size()) { + return false; } - } else { - - if(sourceObj.getClass() != targetObj.getClass()){ - return false; + for (int i = 0; i < source.size(); i++) { + Object sourceObj = source.get(i); + Object targetObj = target.get(i); + if ((sourceObj == null && targetObj != null) || sourceObj != null && targetObj == null) { + return false; + } + if (!handleSourceAndTargetObjects(sourceObj, targetObj)) { + return false; + } } + return true; + } - if (!sourceObj.equals(targetObj)) { - return false; + public static boolean handleSourceAndTargetObjects(Object sourceObj, Object targetObj) { + if (sourceObj == null && targetObj == null) { + return true; + } + if (sourceObj == null && targetObj != null) { + return false; + } + if (sourceObj.getClass().equals(targetObj.getClass())) { + if (sourceObj instanceof Map) { + if (!compareMaps((Map) sourceObj, (Map) targetObj)) { + return false; + } + } else if (sourceObj instanceof List) { + if (!compareLists((List) sourceObj, (List) targetObj)) { + return false; + } + } else { + if (sourceObj.getClass() != targetObj.getClass()) { + return false; + } + if (!sourceObj.equals(targetObj)) { + return false; + } + } } - } + return true; } - return true; - } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/PropertiesUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/PropertiesUtils.java index 351e2a343d..15f56b9b20 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/PropertiesUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/PropertiesUtils.java @@ -13,10 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.utils; +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + import com.google.common.base.CharMatcher; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.collections4.ListUtils; @@ -31,20 +43,6 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; - public class PropertiesUtils { private PropertiesUtils() { @@ -57,41 +55,29 @@ public class PropertiesUtils { properties = new ArrayList<>(); } Set serviceProperties = new HashSet<>(properties); - SetUtils.emptyIfNull(serviceProperties) - .forEach(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, - service.getInputs())); - Set inputs = ListUtils.emptyIfNull(service.getInputs()).stream() - .map(PropertyDefinition::new) - .collect(Collectors.toSet()); + SetUtils.emptyIfNull(serviceProperties).forEach(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, service.getInputs())); + Set inputs = ListUtils.emptyIfNull(service.getInputs()).stream().map(PropertyDefinition::new).collect(Collectors.toSet()); serviceProperties.addAll(inputs); - serviceProperties = serviceProperties.stream() - .filter(distinctByKey(PropertyDefinition::getName)) - .collect(Collectors.toSet()); + serviceProperties = serviceProperties.stream().filter(distinctByKey(PropertyDefinition::getName)).collect(Collectors.toSet()); return new ArrayList<>(serviceProperties); } - public static PropertyDefinition resolvePropertyValueFromInput(PropertyDefinition propertyDefinition, - List componentInputs) { + public static PropertyDefinition resolvePropertyValueFromInput(PropertyDefinition propertyDefinition, List componentInputs) { if (Objects.isNull(propertyDefinition) || CollectionUtils.isEmpty(componentInputs)) { return propertyDefinition; } - Optional mappedInput = componentInputs.stream() - .filter(componentInput -> Objects.nonNull(componentInput.getPropertyId()) - && componentInput.getPropertyId().equals(propertyDefinition.getUniqueId())) - .findFirst(); + Optional mappedInput = componentInputs.stream().filter( + componentInput -> Objects.nonNull(componentInput.getPropertyId()) && componentInput.getPropertyId() + .equals(propertyDefinition.getUniqueId())).findFirst(); mappedInput.ifPresent(inputDefinition -> propertyDefinition.setValue(inputDefinition.getValue())); return propertyDefinition; } - - public static Optional isCapabilityProperty(String propertyUniqueId, - Component containerComponent) { - + public static Optional isCapabilityProperty(String propertyUniqueId, Component containerComponent) { Optional> capPropertiesOptional = getCapProperties(containerComponent); - - if(capPropertiesOptional.isPresent()) { - return capPropertiesOptional.get().stream().filter(propertyDefinition -> - propertyDefinition.getUniqueId().equals(propertyUniqueId)).findAny(); + if (capPropertiesOptional.isPresent()) { + return capPropertiesOptional.get().stream().filter(propertyDefinition -> propertyDefinition.getUniqueId().equals(propertyUniqueId)) + .findAny(); } else { return Optional.empty(); } @@ -99,50 +85,44 @@ public class PropertiesUtils { private static Optional> getCapProperties(Component containerComponent) { Map> componentCapabilities = containerComponent.getCapabilities(); - if(MapUtils.isEmpty(componentCapabilities)){ + if (MapUtils.isEmpty(componentCapabilities)) { return Optional.empty(); } - List capabilityDefinitionList = componentCapabilities.values() - .stream().flatMap(Collection::stream).collect(Collectors.toList()); - if(CollectionUtils.isEmpty(capabilityDefinitionList)){ + List capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(capabilityDefinitionList)) { return Optional.empty(); } - List allComponentInstanceCapProperties= new ArrayList<>(); - capabilityDefinitionList.stream().filter(capabilityDefinition -> CollectionUtils.isNotEmpty(capabilityDefinition - .getProperties())).collect(Collectors.toList()).forEach(capabilityDefinition -> - allComponentInstanceCapProperties.addAll(capabilityDefinition.getProperties())); + List allComponentInstanceCapProperties = new ArrayList<>(); + capabilityDefinitionList.stream().filter(capabilityDefinition -> CollectionUtils.isNotEmpty(capabilityDefinition.getProperties())) + .collect(Collectors.toList()) + .forEach(capabilityDefinition -> allComponentInstanceCapProperties.addAll(capabilityDefinition.getProperties())); return Optional.of(allComponentInstanceCapProperties); } public static Optional getPropertyCapabilityOfChildInstance(String propertyParentUniqueId, - Map> - componentCapabilities) { - if(MapUtils.isEmpty(componentCapabilities)){ + Map> componentCapabilities) { + if (MapUtils.isEmpty(componentCapabilities)) { return Optional.empty(); } - List capabilityDefinitionList = componentCapabilities.values() - .stream().flatMap(Collection::stream).collect(Collectors.toList()); - if(CollectionUtils.isEmpty(capabilityDefinitionList)){ + List capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(capabilityDefinitionList)) { return Optional.empty(); } - return capabilityDefinitionList.stream() - .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId) && - capabilityDefinition.getPath().size() == 1) - .findAny(); + return capabilityDefinitionList.stream().filter( + capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId) && capabilityDefinition.getPath().size() == 1) + .findAny(); } public static Optional getPropertyCapabilityFromAllCapProps(String propertyParentUniqueId, - List - capabilityDefinitionList) { - return capabilityDefinitionList.stream() - .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId)) - .findAny(); + List capabilityDefinitionList) { + return capabilityDefinitionList.stream().filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId)) + .findAny(); } public static boolean isNodeProperty(String propertyName, List properties) { - - return !CollectionUtils.isEmpty(properties) && properties.stream().anyMatch(property -> property.getName() - .equals(propertyName)); + return !CollectionUtils.isEmpty(properties) && properties.stream().anyMatch(property -> property.getName().equals(propertyName)); } private static Predicate distinctByKey(Function keyExtractor) { @@ -152,31 +132,28 @@ public class PropertiesUtils { public static Optional getPropertyByInputId(Component component, String inputId) { List componentInputs = component.getInputs(); - if(CollectionUtils.isEmpty(componentInputs)) { + if (CollectionUtils.isEmpty(componentInputs)) { return Optional.empty(); } - Optional inputDefinition = componentInputs.stream().filter(cip -> cip.getUniqueId() - .equals(inputId)).findFirst(); - if(!inputDefinition.isPresent()) { + Optional inputDefinition = componentInputs.stream().filter(cip -> cip.getUniqueId().equals(inputId)).findFirst(); + if (!inputDefinition.isPresent()) { return Optional.empty(); } Optional> capProperties = getCapProperties(component); - if(!capProperties.isPresent()) { + if (!capProperties.isPresent()) { return Optional.empty(); } - - return capProperties.get().stream().filter(capProp -> CollectionUtils.isNotEmpty(capProp.getGetInputValues()) && - capProp.getGetInputValues().stream().anyMatch(capPropInp -> capPropInp.getInputId().equals(inputId)) && - capProp.getUniqueId().equals(inputDefinition.get().getPropertyId())).findAny(); + return capProperties.get().stream().filter( + capProp -> CollectionUtils.isNotEmpty(capProp.getGetInputValues()) && capProp.getGetInputValues().stream() + .anyMatch(capPropInp -> capPropInp.getInputId().equals(inputId)) && capProp.getUniqueId() + .equals(inputDefinition.get().getPropertyId())).findAny(); } - public static List getCapabilityProperty(ComponentInstanceProperty capabilityProperty, - String inputId) { + public static List getCapabilityProperty(ComponentInstanceProperty capabilityProperty, String inputId) { List resList = new ArrayList<>(); List inputsValues = capabilityProperty.getGetInputValues(); - if (CollectionUtils.isNotEmpty(inputsValues) && inputsValues.stream().anyMatch(inputData -> - isGetInputValueForInput(inputData, inputId))) { - resList.add(capabilityProperty); + if (CollectionUtils.isNotEmpty(inputsValues) && inputsValues.stream().anyMatch(inputData -> isGetInputValueForInput(inputData, inputId))) { + resList.add(capabilityProperty); } return resList; } @@ -192,6 +169,7 @@ public class PropertiesUtils { /** * Trim " and ' quotes + * * @return String */ public static String trimQuotes(String incomingString) { 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 index 929cd46051..ec414b9fbb 100644 --- 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 @@ -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. @@ -17,39 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.utils; -import org.apache.tinkerpop.shaded.minlog.Log; - -import javax.validation.constraints.NotNull; import java.security.SecureRandom; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.validation.constraints.NotNull; +import org.apache.tinkerpop.shaded.minlog.Log; public class Utils { private static final Pattern COUNTER_PATTERN = Pattern.compile("\\d+$"); private static final SecureRandom random = new SecureRandom(); - - private Utils() {} + private Utils() { + } public static int getNextCounter(@NotNull List existingValues) { if (existingValues.isEmpty()) { return 0; } try { - return 1 + existingValues.stream() - .map(COUNTER_PATTERN::matcher) - .filter(Matcher::find) - .map(matcher -> matcher.group(0)) - .mapToInt(Integer::parseInt) - .max() - .orElse(0); - } - catch (Exception e) { + return 1 + 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); return random.nextInt(100) + 50; } 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 index 5674c2b4cb..e1f902dee6 100644 --- 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 @@ -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. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; +import java.util.ArrayList; +import java.util.List; 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.be.user.Role; -import java.util.ArrayList; -import java.util.List; - @org.springframework.stereotype.Component public class AccessValidations { @@ -39,10 +37,10 @@ public class AccessValidations { this.componentValidations = componentValidations; } - public Component validateUserCanRetrieveComponentData(String componentId, String componentType, String userId, String actionContext) { + public Component validateUserCanRetrieveComponentData(String componentId, String componentType, String userId, String actionContext) { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); retrieveUser(userId, actionContext); - return componentValidations.getComponent(componentId, componentTypeEnum); + return componentValidations.getComponent(componentId, componentTypeEnum); } public Component validateUserCanWorkOnComponent(String componentId, ComponentTypeEnum componentType, String userId, String actionContext) { @@ -61,12 +59,11 @@ public class AccessValidations { retrieveUser(userId, context); } - public void validateUserExist(String userId, String actionContext) { userValidations.validateUserExists(userId); } - public User userIsAdminOrDesigner(String userId, String actionContext){ + public User userIsAdminOrDesigner(String userId, String actionContext) { User user = retrieveUser(userId, actionContext); validateUserIsAdminOrDesigner(user); return user; @@ -82,5 +79,4 @@ public class AccessValidations { roles.add(Role.DESIGNER); userValidations.validateUserRole(user, roles); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AnnotationValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AnnotationValidator.java index 428d6d9d19..b4f6bbe7db 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AnnotationValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AnnotationValidator.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. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.components.impl.ResourceImportManager; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; import org.openecomp.sdc.be.datatypes.elements.Annotation; @@ -32,25 +34,17 @@ import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - @Component public class AnnotationValidator { - + private static final Logger log = Logger.getLogger(ResourceImportManager.class); private final PropertyValidator propertyValidator; private final ExceptionUtils exceptionUtils; private final ApplicationDataTypeCache dataTypeCache; private final ComponentsUtils componentsUtils; - private static final Logger log = Logger.getLogger(ResourceImportManager.class); - - - public AnnotationValidator(PropertyValidator propertyValidator - , ExceptionUtils exceptionUtils, ApplicationDataTypeCache dataTypeCache - ,ComponentsUtils componentsUtils) { + public AnnotationValidator(PropertyValidator propertyValidator, ExceptionUtils exceptionUtils, ApplicationDataTypeCache dataTypeCache, + ComponentsUtils componentsUtils) { this.propertyValidator = propertyValidator; this.exceptionUtils = exceptionUtils; this.dataTypeCache = dataTypeCache; @@ -59,9 +53,8 @@ public class AnnotationValidator { public List validateAnnotationsProperties(Annotation annotation, AnnotationTypeDefinition dbAnnotationTypeDefinition) { List validAnnotations = new ArrayList<>(); - if (annotation != null && propertiesValidator( - annotation.getProperties(), dbAnnotationTypeDefinition.getProperties())) { - validAnnotations.add(annotation); + if (annotation != null && propertiesValidator(annotation.getProperties(), dbAnnotationTypeDefinition.getProperties())) { + validAnnotations.add(annotation); } return validAnnotations; } @@ -71,14 +64,9 @@ public class AnnotationValidator { if (properties == null || dbAnnotationTypeDefinitionProperties == null) { return false; } - properties.stream() - .forEach(property -> propertyDefinitionsList.add(new PropertyDefinition(property))); - Map allDataTypes = dataTypeCache.getAll() - .left() - .on( error -> exceptionUtils - .rollBackAndThrow(error)); + properties.stream().forEach(property -> propertyDefinitionsList.add(new PropertyDefinition(property))); + Map allDataTypes = dataTypeCache.getAll().left().on(error -> exceptionUtils.rollBackAndThrow(error)); propertyValidator.thinPropertiesValidator(propertyDefinitionsList, dbAnnotationTypeDefinitionProperties, allDataTypes); return true; } - } 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 index 7f217b95b1..da8e8bbf4d 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; import lombok.Getter; @@ -27,11 +26,7 @@ import lombok.Getter; */ @Getter public enum ApiResourceEnum { - - ENVIRONMENT_ID("Environment ID"), - RESOURCE_ID("Resource ID"), - SERVICE_ID("Service ID"); - + ENVIRONMENT_ID("Environment ID"), RESOURCE_ID("Resource ID"), SERVICE_ID("Service ID"); private String value; ApiResourceEnum(String value) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/CapabilitiesValidation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/CapabilitiesValidation.java index 2c69ee5b38..3f53f6b993 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/CapabilitiesValidation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/CapabilitiesValidation.java @@ -13,10 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.validation; import fj.data.Either; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -28,26 +33,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - @Component("capabilitiesValidation") public class CapabilitiesValidation { + private static final Logger LOGGER = LoggerFactory.getLogger(CapabilitiesValidation.class); private static final String CAPABILITY_NOT_FOUND_IN_COMPONENT = "Capability not found in component {} "; private static final Pattern NAME_VALIDATION_REGEX_PATTERN = Pattern.compile("^[a-zA-Z0-9_.]*$"); - public Either validateCapabilities( - Collection capabilities, - org.openecomp.sdc.be.model.Component component, boolean isUpdate) { - - for(CapabilityDefinition capabilityDefinition : capabilities) { - Either validateCapabilityResponse = validateCapability(capabilityDefinition, - component, isUpdate); + public Either validateCapabilities(Collection capabilities, + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { + for (CapabilityDefinition capabilityDefinition : capabilities) { + Either validateCapabilityResponse = validateCapability(capabilityDefinition, component, isUpdate); if (validateCapabilityResponse.isRight()) { return validateCapabilityResponse; } @@ -56,29 +52,25 @@ public class CapabilitiesValidation { } private Either validateCapability(CapabilityDefinition capabilityDefinition, - org.openecomp.sdc.be.model.Component component, - boolean isUpdate) { + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { ResponseFormatManager responseFormatManager = getResponseFormatManager(); - - if(isUpdate) { - Either capabilityExistValidationEither - = isCapabilityExist(capabilityDefinition, responseFormatManager, component); + if (isUpdate) { + Either capabilityExistValidationEither = isCapabilityExist(capabilityDefinition, responseFormatManager, + component); if (capabilityExistValidationEither.isRight()) { return Either.right(capabilityExistValidationEither.right().value()); } } - Either capabilityNameValidationResponse - = validateCapabilityName(capabilityDefinition, responseFormatManager, component, isUpdate); + Either capabilityNameValidationResponse = validateCapabilityName(capabilityDefinition, responseFormatManager, + component, isUpdate); if (capabilityNameValidationResponse.isRight()) { return Either.right(capabilityNameValidationResponse.right().value()); } - Either capabilityTypeEmptyEither = - isCapabilityTypeEmpty(responseFormatManager, capabilityDefinition.getType()); + Either capabilityTypeEmptyEither = isCapabilityTypeEmpty(responseFormatManager, capabilityDefinition.getType()); if (capabilityTypeEmptyEither.isRight()) { return Either.right(capabilityTypeEmptyEither.right().value()); } - Either capabilityOccurrencesValidationEither = - validateOccurrences(capabilityDefinition, responseFormatManager); + Either capabilityOccurrencesValidationEither = validateOccurrences(capabilityDefinition, responseFormatManager); if (capabilityOccurrencesValidationEither.isRight()) { return Either.right(capabilityOccurrencesValidationEither.right().value()); } @@ -89,9 +81,9 @@ public class CapabilitiesValidation { ResponseFormatManager responseFormatManager) { String maxOccurrences = capabilityDefinition.getMaxOccurrences(); String minOccurrences = capabilityDefinition.getMinOccurrences(); - if(maxOccurrences != null && minOccurrences != null) { - Either capabilityOccurrencesValidationEither = - validateOccurrences(responseFormatManager, minOccurrences, maxOccurrences); + if (maxOccurrences != null && minOccurrences != null) { + Either capabilityOccurrencesValidationEither = validateOccurrences(responseFormatManager, minOccurrences, + maxOccurrences); if (capabilityOccurrencesValidationEither.isRight()) { return Either.right(capabilityOccurrencesValidationEither.right().value()); } @@ -99,32 +91,26 @@ public class CapabilitiesValidation { return Either.left(Boolean.TRUE); } - private Either isCapabilityExist(CapabilityDefinition definition, - ResponseFormatManager responseFormatManager, + private Either isCapabilityExist(CapabilityDefinition definition, ResponseFormatManager responseFormatManager, org.openecomp.sdc.be.model.Component component) { Map> componentCapabilities = component.getCapabilities(); - if(MapUtils.isEmpty(componentCapabilities)){ + if (MapUtils.isEmpty(componentCapabilities)) { LOGGER.error(CAPABILITY_NOT_FOUND_IN_COMPONENT, component.getUniqueId()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .CAPABILITY_NOT_FOUND, component.getUniqueId()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, component.getUniqueId()); return Either.right(errorResponse); } - - List capabilityDefinitionList = componentCapabilities.values() - .stream().flatMap(Collection::stream).collect(Collectors.toList()); - if(CollectionUtils.isEmpty(capabilityDefinitionList)){ + List capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(capabilityDefinitionList)) { LOGGER.error(CAPABILITY_NOT_FOUND_IN_COMPONENT, component.getUniqueId()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .CAPABILITY_NOT_FOUND, component.getUniqueId()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, component.getUniqueId()); return Either.right(errorResponse); } - boolean isCapabilityExist = capabilityDefinitionList.stream().anyMatch(capabilityDefinition -> - capabilityDefinition.getUniqueId().equalsIgnoreCase(definition.getUniqueId())); - - if(!isCapabilityExist) { + boolean isCapabilityExist = capabilityDefinitionList.stream() + .anyMatch(capabilityDefinition -> capabilityDefinition.getUniqueId().equalsIgnoreCase(definition.getUniqueId())); + if (!isCapabilityExist) { LOGGER.error(CAPABILITY_NOT_FOUND_IN_COMPONENT, component.getUniqueId()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .CAPABILITY_NOT_FOUND, component.getUniqueId()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, component.getUniqueId()); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); @@ -132,36 +118,30 @@ public class CapabilitiesValidation { private Either validateCapabilityName(CapabilityDefinition capabilityDefinition, ResponseFormatManager responseFormatManager, - org.openecomp.sdc.be.model.Component component, - boolean isUpdate) { - Either capabilityNameEmptyEither = - isCapabilityNameEmpty(responseFormatManager, capabilityDefinition.getName()); + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { + Either capabilityNameEmptyEither = isCapabilityNameEmpty(responseFormatManager, capabilityDefinition.getName()); if (capabilityNameEmptyEither.isRight()) { return Either.right(capabilityNameEmptyEither.right().value()); } - - Either capabilityNameRegexValidationResponse = - isCapabilityNameRegexValid(responseFormatManager, capabilityDefinition.getName()); + Either capabilityNameRegexValidationResponse = isCapabilityNameRegexValid(responseFormatManager, + capabilityDefinition.getName()); if (capabilityNameRegexValidationResponse.isRight()) { return Either.right(capabilityNameRegexValidationResponse.right().value()); } - - Either operationTypeUniqueResponse - = validateCapabilityNameUnique(capabilityDefinition, component, isUpdate ); - if(operationTypeUniqueResponse.isRight()) { + Either operationTypeUniqueResponse = validateCapabilityNameUnique(capabilityDefinition, component, isUpdate); + if (operationTypeUniqueResponse.isRight()) { return Either.right(operationTypeUniqueResponse.right().value()); } if (!operationTypeUniqueResponse.left().value()) { LOGGER.error("Capability name {} already in use ", capabilityDefinition.getName()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .CAPABILITY_NAME_ALREADY_IN_USE, capabilityDefinition.getName()); + ResponseFormat errorResponse = responseFormatManager + .getResponseFormat(ActionStatus.CAPABILITY_NAME_ALREADY_IN_USE, capabilityDefinition.getName()); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either isCapabilityNameEmpty(ResponseFormatManager responseFormatManager, - String capabilityName) { + private Either isCapabilityNameEmpty(ResponseFormatManager responseFormatManager, String capabilityName) { if (StringUtils.isEmpty(capabilityName)) { LOGGER.error("Capability Name is mandatory"); ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_NAME_MANDATORY); @@ -170,8 +150,7 @@ public class CapabilitiesValidation { return Either.left(Boolean.TRUE); } - private Either isCapabilityTypeEmpty(ResponseFormatManager responseFormatManager, - String capabilityType) { + private Either isCapabilityTypeEmpty(ResponseFormatManager responseFormatManager, String capabilityType) { if (StringUtils.isEmpty(capabilityType)) { LOGGER.error("Capability type is mandatory"); ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_TYPE_MANDATORY); @@ -180,11 +159,10 @@ public class CapabilitiesValidation { return Either.left(Boolean.TRUE); } - private Either validateOccurrences (ResponseFormatManager responseFormatManager, - String minOccurrences, String maxOccurrences ) { + private Either validateOccurrences(ResponseFormatManager responseFormatManager, String minOccurrences, + String maxOccurrences) { try { - if (StringUtils.isNotEmpty(maxOccurrences) && "UNBOUNDED".equalsIgnoreCase(maxOccurrences) - && Integer.parseInt(minOccurrences) >= 0) { + if (StringUtils.isNotEmpty(maxOccurrences) && "UNBOUNDED".equalsIgnoreCase(maxOccurrences) && Integer.parseInt(minOccurrences) >= 0) { return Either.left(Boolean.TRUE); } else if (Integer.parseInt(minOccurrences) < 0) { LOGGER.debug("Invalid occurrences format.low_bound occurrence negative {}", minOccurrences); @@ -192,8 +170,8 @@ public class CapabilitiesValidation { return Either.right(responseFormat); } else if (Integer.parseInt(maxOccurrences) < Integer.parseInt(minOccurrences)) { LOGGER.error("Capability maxOccurrences should be greater than minOccurrences"); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .MAX_OCCURRENCES_SHOULD_BE_GREATER_THAN_MIN_OCCURRENCES); + ResponseFormat errorResponse = responseFormatManager + .getResponseFormat(ActionStatus.MAX_OCCURRENCES_SHOULD_BE_GREATER_THAN_MIN_OCCURRENCES); return Either.right(errorResponse); } } catch (NumberFormatException ex) { @@ -205,40 +183,36 @@ public class CapabilitiesValidation { } private Either validateCapabilityNameUnique(CapabilityDefinition capabilityDefinition, - org.openecomp.sdc.be.model.Component component, - boolean isUpdate) { + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { boolean isCapabilityNameUnique = false; Map> componentCapabilities = component.getCapabilities(); - if(MapUtils.isEmpty(componentCapabilities)){ + if (MapUtils.isEmpty(componentCapabilities)) { return Either.left(true); } - List capabilityDefinitionList = componentCapabilities.values() - .stream().flatMap(Collection::stream).collect(Collectors.toList()); - if(CollectionUtils.isEmpty(capabilityDefinitionList)){ + List capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(capabilityDefinitionList)) { return Either.left(true); } Map capabilityNameMap = new HashMap<>(); capabilityDefinitionList.forEach(capability -> capabilityNameMap.put(capability.getUniqueId(), capability.getName())); - - if (!capabilityNameMap.values().contains(capabilityDefinition.getName())){ + if (!capabilityNameMap.values().contains(capabilityDefinition.getName())) { isCapabilityNameUnique = true; } - if (!isCapabilityNameUnique && isUpdate){ - List> capNamesEntries = capabilityNameMap.entrySet().stream().filter(entry -> - entry.getValue().equalsIgnoreCase(capabilityDefinition.getName())).collect(Collectors.toList()); - if(capNamesEntries.size() == 1 && capNamesEntries.get(0).getKey().equals(capabilityDefinition.getUniqueId())) { + if (!isCapabilityNameUnique && isUpdate) { + List> capNamesEntries = capabilityNameMap.entrySet().stream() + .filter(entry -> entry.getValue().equalsIgnoreCase(capabilityDefinition.getName())).collect(Collectors.toList()); + if (capNamesEntries.size() == 1 && capNamesEntries.get(0).getKey().equals(capabilityDefinition.getUniqueId())) { isCapabilityNameUnique = true; } } return Either.left(isCapabilityNameUnique); } - private Either isCapabilityNameRegexValid(ResponseFormatManager responseFormatManager, - String capabilityName) { + private Either isCapabilityNameRegexValid(ResponseFormatManager responseFormatManager, String capabilityName) { if (!isValidCapabilityName(capabilityName)) { LOGGER.error("Capability name {} is invalid, Only alphanumeric chars, underscore and dot allowed", capabilityName); - ResponseFormat errorResponse = responseFormatManager - .getResponseFormat(ActionStatus.INVALID_CAPABILITY_NAME, capabilityName); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CAPABILITY_NAME, capabilityName); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); @@ -251,5 +225,4 @@ public class CapabilitiesValidation { protected ResponseFormatManager getResponseFormatManager() { return ResponseFormatManager.getInstance(); } - } 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 bdd7f656b3..10bb1d0ea6 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 @@ -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. @@ -19,9 +19,14 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.components.validation; +import static java.util.stream.Collectors.toList; + +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -38,13 +43,6 @@ 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; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static java.util.stream.Collectors.toList; - @org.springframework.stereotype.Component public class ComponentValidations { @@ -55,17 +53,13 @@ public class ComponentValidations { } public Optional getComponentInstance(Component component, String instanceId) { - return component.getComponentInstances() - .stream() - .filter(ci -> ci.getUniqueId().equals(instanceId)) - .findFirst(); + return component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst(); } public static boolean validateComponentInstanceExist(Component component, String instanceId) { return Optional.ofNullable(component.getComponentInstances()) - .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(toList())) - .filter(instancesIds -> instancesIds.contains(instanceId)) - .isPresent(); + .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(toList())) + .filter(instancesIds -> instancesIds.contains(instanceId)).isPresent(); } public static String getNormalizedName(ToscaDataDefinition toscaDataDefinition) { @@ -74,8 +68,8 @@ public class ComponentValidations { } /** - * The following logic is applied: - * For each name new or existing name we look at the normalized name which is used in Tosca representation + * 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 @@ -84,7 +78,6 @@ public class ComponentValidations { 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 } @@ -92,17 +85,11 @@ public class ComponentValidations { List componentInstances = component.getComponentInstances(); Set existingNames = new HashSet<>(); if (CollectionUtils.isNotEmpty(groups)) { - List existingGroupNames = groups - .stream() - .map(ComponentValidations::getNormalizedName) - .collect(toList()); + 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()); + List existingInstanceNames = componentInstances.stream().map(ComponentValidations::getNormalizedName).collect(toList()); existingNames.addAll(existingInstanceNames); } return !existingNames.contains(normalizedNewName); @@ -110,9 +97,11 @@ public class ComponentValidations { void validateComponentIsCheckedOutByUser(Component component, String userId) { if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { - throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, component.getComponentType().name(), component.getName(), component.getLifecycleState().name()); + throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, component.getComponentType().name(), component.getName(), + component.getLifecycleState().name()); } } + Component validateComponentIsCheckedOutByUser(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { Component component = getComponent(componentId, componentTypeEnum); validateComponentIsCheckedOutByUser(component, userId); @@ -120,17 +109,14 @@ public class ComponentValidations { } Component getComponent(String componentId, ComponentTypeEnum componentType) { - Component component = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView()) - .left() - .on(storageOperationStatus -> onToscaOperationError(storageOperationStatus, componentId)); - + Component component = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView()).left() + .on(storageOperationStatus -> onToscaOperationError(storageOperationStatus, componentId)); validateComponentType(component, componentType); - return component; } private void validateComponentType(Component component, ComponentTypeEnum componentType) { - if (componentType!=component.getComponentType()) { + if (componentType != component.getComponentType()) { throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE); } } @@ -138,5 +124,4 @@ public class ComponentValidations { private Component onToscaOperationError(StorageOperationStatus storageOperationStatus, String componentId) { throw new StorageException(storageOperationStatus, componentId); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java index b876782ce4..419430beaa 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java @@ -13,11 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.validation; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationOutputName; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOtherOperationOutputsOfComponent; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput; +import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty; + import com.google.common.collect.Sets; import fj.data.Either; +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.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -35,262 +51,194 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -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.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationOutputName; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOtherOperationOutputsOfComponent; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput; -import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty; - @Component("interfaceOperationValidation") public class InterfaceOperationValidation { private static final String TYPE_VALIDATION_REGEX = "^[a-zA-Z0-9_]{1,200}$"; - private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceOperationValidation.class); - public Either validateInterfaceOperations( - InterfaceDefinition inputInterfaceDefinition, org.openecomp.sdc.be.model.Component component, - InterfaceDefinition storedInterfaceDefinition, Map globalInterfaceTypes, - boolean isUpdate) { - - Either validateAllowedOperationsOnGlobalInterfaceType = - validateAllowedOperationsOnGlobalInterfaceType(inputInterfaceDefinition, globalInterfaceTypes); + public Either validateInterfaceOperations(InterfaceDefinition inputInterfaceDefinition, + org.openecomp.sdc.be.model.Component component, + InterfaceDefinition storedInterfaceDefinition, + Map globalInterfaceTypes, boolean isUpdate) { + Either validateAllowedOperationsOnGlobalInterfaceType = validateAllowedOperationsOnGlobalInterfaceType( + inputInterfaceDefinition, globalInterfaceTypes); if (validateAllowedOperationsOnGlobalInterfaceType.isRight()) { return validateAllowedOperationsOnGlobalInterfaceType; } - - Either validateOperationNameUniqueness = - validateOperationNameUniquenessInCollection(inputInterfaceDefinition.getOperationsMap().values()); + Either validateOperationNameUniqueness = validateOperationNameUniquenessInCollection( + inputInterfaceDefinition.getOperationsMap().values()); if (validateOperationNameUniqueness.isRight()) { return validateOperationNameUniqueness; } - for (Operation interfaceOperation : inputInterfaceDefinition.getOperationsMap().values()) { - Either interfaceOperationValidatorResponse = validateInterfaceOperation( - interfaceOperation, storedInterfaceDefinition, inputInterfaceDefinition, component, isUpdate); + Either interfaceOperationValidatorResponse = validateInterfaceOperation(interfaceOperation, + storedInterfaceDefinition, inputInterfaceDefinition, component, isUpdate); if (interfaceOperationValidatorResponse.isRight()) { return interfaceOperationValidatorResponse; } } - return Either.left(Boolean.TRUE); } - public Either validateDeleteOperationContainsNoMappedOutput( - Operation interfaceOperationToDelete, org.openecomp.sdc.be.model.Component component, - InterfaceDefinition storedInterfaceDefinition) { + public Either validateDeleteOperationContainsNoMappedOutput(Operation interfaceOperationToDelete, + org.openecomp.sdc.be.model.Component component, + InterfaceDefinition storedInterfaceDefinition) { ResponseFormatManager responseFormatManager = getResponseFormatManager(); - List existingOperationOutputs = - getInterfaceOperationOutputs(interfaceOperationToDelete.getUniqueId(), component.getInterfaces()); + List existingOperationOutputs = getInterfaceOperationOutputs(interfaceOperationToDelete.getUniqueId(), + component.getInterfaces()); if (existingOperationOutputs.isEmpty()) { return Either.left(Boolean.TRUE); } String mappedOutputPrefix = storedInterfaceDefinition.getType() + "." + interfaceOperationToDelete.getName(); - List interfaceOperationInputs = - getOtherOperationInputsOfComponent(mappedOutputPrefix, component.getInterfaces()); + List interfaceOperationInputs = getOtherOperationInputsOfComponent(mappedOutputPrefix, component.getInterfaces()); Set mappedOutputsInDeletedOperation = new HashSet<>(); - Set existingOperationOutputNames = existingOperationOutputs.stream() - .map(OperationOutputDefinition::getName) - .collect(Collectors.toSet()); + Set existingOperationOutputNames = existingOperationOutputs.stream().map(OperationOutputDefinition::getName) + .collect(Collectors.toSet()); for (String existingOperationOutputName : existingOperationOutputNames) { - Set matchedOutputsMappedToInputs = interfaceOperationInputs.stream() - .filter(operationInputDefinition -> operationInputDefinition.getInputId() - .equals(mappedOutputPrefix + "." + existingOperationOutputName)) - .map(operationInputDefinition -> getOperationOutputName(operationInputDefinition.getInputId())) - .collect(Collectors.toSet()); + Set matchedOutputsMappedToInputs = interfaceOperationInputs.stream().filter( + operationInputDefinition -> operationInputDefinition.getInputId().equals(mappedOutputPrefix + "." + existingOperationOutputName)) + .map(operationInputDefinition -> getOperationOutputName(operationInputDefinition.getInputId())).collect(Collectors.toSet()); mappedOutputsInDeletedOperation.addAll(matchedOutputsMappedToInputs); } - if (CollectionUtils.isNotEmpty(mappedOutputsInDeletedOperation)) { return getMappedOutputErrorResponse(responseFormatManager, mappedOutputsInDeletedOperation, - "Cannot delete interface operation with output(s) '{}' mapped to another operation input", - ActionStatus.INTERFACE_OPERATION_DELETE_WITH_MAPPED_OUTPUT); + "Cannot delete interface operation with output(s) '{}' mapped to another operation input", + ActionStatus.INTERFACE_OPERATION_DELETE_WITH_MAPPED_OUTPUT); } return Either.left(Boolean.TRUE); } - private Either validateAllowedOperationsOnGlobalInterfaceType( - InterfaceDefinition interfaceDefinition, Map globalInterfaceTypes) { - + private Either validateAllowedOperationsOnGlobalInterfaceType(InterfaceDefinition interfaceDefinition, + Map globalInterfaceTypes) { if (globalInterfaceTypes == null) { return Either.left(Boolean.TRUE); } - boolean isOperationValidOnGlobalInterfaceType = Stream.of(interfaceDefinition) - .filter(interfaceDef -> globalInterfaceTypes.values().stream().anyMatch(interfaceDef1 -> - interfaceDef1.getType().equalsIgnoreCase(interfaceDef.getType()))) - .flatMap(interfaceDef -> interfaceDef.getOperationsMap().values().stream().map(Operation::getName)) - .allMatch(operationName -> globalInterfaceTypes.values().stream() - .flatMap(interfaceDef -> interfaceDef.getOperationsMap().keySet().stream()) - .anyMatch(opName -> opName.equalsIgnoreCase(operationName))); + boolean isOperationValidOnGlobalInterfaceType = Stream.of(interfaceDefinition).filter(interfaceDef -> globalInterfaceTypes.values().stream() + .anyMatch(interfaceDef1 -> interfaceDef1.getType().equalsIgnoreCase(interfaceDef.getType()))) + .flatMap(interfaceDef -> interfaceDef.getOperationsMap().values().stream().map(Operation::getName)).allMatch( + operationName -> globalInterfaceTypes.values().stream().flatMap(interfaceDef -> interfaceDef.getOperationsMap().keySet().stream()) + .anyMatch(opName -> opName.equalsIgnoreCase(operationName))); if (!isOperationValidOnGlobalInterfaceType) { return Either.right(getResponseFormatManager() - .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INVALID_FOR_GLOBAL_TYPE, - interfaceDefinition.getType())); + .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INVALID_FOR_GLOBAL_TYPE, interfaceDefinition.getType())); } return Either.left(Boolean.TRUE); } - private Either validateOperationNameUniquenessInCollection( - Collection operationList) { + private Either validateOperationNameUniquenessInCollection(Collection operationList) { HashSet operationNames = new HashSet<>(); for (Operation operation : operationList) { if (!operationNames.add(operation.getName())) { - return Either.right(getResponseFormatManager() - .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, - operation.getName())); + return Either + .right(getResponseFormatManager().getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, operation.getName())); } } return Either.left(Boolean.TRUE); } - private Either validateInterfaceOperation(Operation interfaceOperation, - InterfaceDefinition storedInterfaceDefinition, InterfaceDefinition inputInterfaceDefinition, - org.openecomp.sdc.be.model.Component component, boolean isUpdate) { - + private Either validateInterfaceOperation(Operation interfaceOperation, InterfaceDefinition storedInterfaceDefinition, + InterfaceDefinition inputInterfaceDefinition, + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { ResponseFormatManager responseFormatManager = getResponseFormatManager(); - Either interfaceOperationTypeResponse = - isInterfaceOperationTypeValid(interfaceOperation, responseFormatManager, storedInterfaceDefinition, - isUpdate); + Either interfaceOperationTypeResponse = isInterfaceOperationTypeValid(interfaceOperation, responseFormatManager, + storedInterfaceDefinition, isUpdate); if (interfaceOperationTypeResponse.isRight()) { return Either.right(interfaceOperationTypeResponse.right().value()); } - - if (null != interfaceOperation.getInputs() - && CollectionUtils.isNotEmpty(interfaceOperation.getInputs().getListToscaDataDefinition())) { - Either inputParametersResponse = - validateInputParameters(interfaceOperation, responseFormatManager); + if (null != interfaceOperation.getInputs() && CollectionUtils.isNotEmpty(interfaceOperation.getInputs().getListToscaDataDefinition())) { + Either inputParametersResponse = validateInputParameters(interfaceOperation, responseFormatManager); if (inputParametersResponse.isRight()) { return Either.right(inputParametersResponse.right().value()); } - - Either inputPropertyExistInComponent = - validateInputPropertyExistInComponent(interfaceOperation, - inputInterfaceDefinition, component, responseFormatManager); + Either inputPropertyExistInComponent = validateInputPropertyExistInComponent(interfaceOperation, + inputInterfaceDefinition, component, responseFormatManager); if (inputPropertyExistInComponent.isRight()) { return Either.right(inputPropertyExistInComponent.right().value()); } } - - if (null != interfaceOperation.getOutputs() - && CollectionUtils.isNotEmpty(interfaceOperation.getOutputs().getListToscaDataDefinition())) { - Either outputParametersResponse = - validateOutputParameters(interfaceOperation, responseFormatManager); + if (null != interfaceOperation.getOutputs() && CollectionUtils.isNotEmpty(interfaceOperation.getOutputs().getListToscaDataDefinition())) { + Either outputParametersResponse = validateOutputParameters(interfaceOperation, responseFormatManager); if (outputParametersResponse.isRight()) { return Either.right(outputParametersResponse.right().value()); } } - if (MapUtils.isNotEmpty(component.getInterfaces()) && isUpdate) { - Either mappedOutputModifiedResponse = - validateMappedOutputNotModified(interfaceOperation, component, inputInterfaceDefinition, - responseFormatManager); + Either mappedOutputModifiedResponse = validateMappedOutputNotModified(interfaceOperation, component, + inputInterfaceDefinition, responseFormatManager); if (mappedOutputModifiedResponse.isRight()) { return Either.right(mappedOutputModifiedResponse.right().value()); } } - return Either.left(Boolean.TRUE); } - private Either validateMappedOutputNotModified(Operation interfaceOperation, - org.openecomp.sdc.be.model.Component component, InterfaceDefinition interfaceDefinition, - ResponseFormatManager responseFormatManager) { - - List existingOperationOutputs = - getInterfaceOperationOutputs(interfaceOperation.getUniqueId(), component.getInterfaces()); + org.openecomp.sdc.be.model.Component component, + InterfaceDefinition interfaceDefinition, + ResponseFormatManager responseFormatManager) { + List existingOperationOutputs = getInterfaceOperationOutputs(interfaceOperation.getUniqueId(), + component.getInterfaces()); if (existingOperationOutputs.isEmpty()) { return Either.left(Boolean.TRUE); } - Set existingOperationOutputNames = existingOperationOutputs.stream() - .map(OperationOutputDefinition::getName) - .collect(Collectors.toSet()); - + Set existingOperationOutputNames = existingOperationOutputs.stream().map(OperationOutputDefinition::getName) + .collect(Collectors.toSet()); ListDataDefinition currentOutputs = interfaceOperation.getOutputs(); Set currentOperationOutputNames = new HashSet<>(); if (currentOutputs != null && !currentOutputs.isEmpty()) { - currentOperationOutputNames = currentOutputs.getListToscaDataDefinition().stream() - .map(OperationOutputDefinition::getName) - .collect(Collectors.toSet()); + currentOperationOutputNames = currentOutputs.getListToscaDataDefinition().stream().map(OperationOutputDefinition::getName) + .collect(Collectors.toSet()); } String mappedOutputPrefix = interfaceDefinition.getType() + "." + interfaceOperation.getName(); //Get the deleted outputs (name changed also equivalent to deleted) Set deletedOutputs = Sets.difference(existingOperationOutputNames, currentOperationOutputNames); - Set deletedMappedOutputs = getModifiedMappedOutputs(deletedOutputs, mappedOutputPrefix, - component.getInterfaces()); - + Set deletedMappedOutputs = getModifiedMappedOutputs(deletedOutputs, mappedOutputPrefix, component.getInterfaces()); if (CollectionUtils.isNotEmpty(deletedMappedOutputs)) { return getMappedOutputErrorResponse(responseFormatManager, deletedMappedOutputs, - "Cannot update or delete interface operation output(s) '{}' mapped to an operation input", - ActionStatus.INTERFACE_OPERATION_MAPPED_OUTPUT_MODIFIED); + "Cannot update or delete interface operation output(s) '{}' mapped to an operation input", + ActionStatus.INTERFACE_OPERATION_MAPPED_OUTPUT_MODIFIED); } - if (currentOutputs != null && !currentOutputs.isEmpty()) { //Get the unchanged outputs based on name to see if other attributes (type/mandatory) have not been changed - Set unchangedOutputNames = Sets.intersection(existingOperationOutputNames, - currentOperationOutputNames); - Set modifiedOutputNames = - getModifiedOutputNames(currentOutputs.getListToscaDataDefinition(), - existingOperationOutputs, unchangedOutputNames); - Set modifiedMappedOutputNames = getModifiedMappedOutputs(modifiedOutputNames, mappedOutputPrefix, - component.getInterfaces()); + Set unchangedOutputNames = Sets.intersection(existingOperationOutputNames, currentOperationOutputNames); + Set modifiedOutputNames = getModifiedOutputNames(currentOutputs.getListToscaDataDefinition(), existingOperationOutputs, + unchangedOutputNames); + Set modifiedMappedOutputNames = getModifiedMappedOutputs(modifiedOutputNames, mappedOutputPrefix, component.getInterfaces()); if (CollectionUtils.isNotEmpty(modifiedMappedOutputNames)) { return getMappedOutputErrorResponse(responseFormatManager, modifiedMappedOutputNames, - "Cannot update or delete interface operation output(s) '{}' mapped to an operation input", - ActionStatus.INTERFACE_OPERATION_MAPPED_OUTPUT_MODIFIED); + "Cannot update or delete interface operation output(s) '{}' mapped to an operation input", + ActionStatus.INTERFACE_OPERATION_MAPPED_OUTPUT_MODIFIED); } } - return Either.left(Boolean.TRUE); } private Set getModifiedMappedOutputs(Set modifiedOutputNames, String mappedOutputPrefix, Map componentInterfaces) { return modifiedOutputNames.stream() - .filter(modifiedOutputName -> isMappedOutputModified(mappedOutputPrefix, modifiedOutputName, - componentInterfaces)) - .map(InterfaceOperationUtils::getOperationOutputName) - .collect(Collectors.toSet()); + .filter(modifiedOutputName -> isMappedOutputModified(mappedOutputPrefix, modifiedOutputName, componentInterfaces)) + .map(InterfaceOperationUtils::getOperationOutputName).collect(Collectors.toSet()); } - private boolean isMappedOutputModified(String mappedOutputPrefix, String outputName, - Map componentInterfaces) { - List interfaceOperationInputs = - getOtherOperationInputsOfComponent(mappedOutputPrefix, componentInterfaces); + private boolean isMappedOutputModified(String mappedOutputPrefix, String outputName, Map componentInterfaces) { + List interfaceOperationInputs = getOtherOperationInputsOfComponent(mappedOutputPrefix, componentInterfaces); return interfaceOperationInputs.stream() - .anyMatch(operationInputDefinition -> operationInputDefinition.getInputId() - .equals(mappedOutputPrefix + "." + outputName)); + .anyMatch(operationInputDefinition -> operationInputDefinition.getInputId().equals(mappedOutputPrefix + "." + outputName)); } private static Set getModifiedOutputNames(List currentOperationOutputs, - List existingOperationOutputs, - Set unchangedOutputNames) { + List existingOperationOutputs, Set unchangedOutputNames) { Set modifiedOutputDefinitionNames = new HashSet<>(); - Map newOutputMap = currentOperationOutputs.stream() - .collect(Collectors.toMap(OperationOutputDefinition::getName, - (OperationOutputDefinition operationOutputDefinition) -> operationOutputDefinition)); - - Map existingOutputMap = existingOperationOutputs.stream() - .collect(Collectors.toMap(OperationOutputDefinition::getName, - (OperationOutputDefinition operationOutputDefinition) -> operationOutputDefinition)); - + Map newOutputMap = currentOperationOutputs.stream().collect( + Collectors.toMap(OperationOutputDefinition::getName, (OperationOutputDefinition operationOutputDefinition) -> operationOutputDefinition)); + Map existingOutputMap = existingOperationOutputs.stream().collect( + Collectors.toMap(OperationOutputDefinition::getName, (OperationOutputDefinition operationOutputDefinition) -> operationOutputDefinition)); for (String outputName : unchangedOutputNames) { OperationOutputDefinition existingOutputDefinition = existingOutputMap.get(outputName); OperationOutputDefinition newOutputDefinition = newOutputMap.get(outputName); - if (!existingOutputDefinition.getType().equals(newOutputDefinition.getType()) - || !existingOutputDefinition.isRequired().equals(newOutputDefinition.isRequired())) { + if (!existingOutputDefinition.getType().equals(newOutputDefinition.getType()) || !existingOutputDefinition.isRequired() + .equals(newOutputDefinition.isRequired())) { modifiedOutputDefinitionNames.add(outputName); } } @@ -298,8 +246,7 @@ public class InterfaceOperationValidation { } private Either getMappedOutputErrorResponse(ResponseFormatManager responseFormatManager, - Set modifiedMappedOutputs, - String message, + Set modifiedMappedOutputs, String message, ActionStatus errorStatus) { String modifiedOutputNameList = String.join(",", modifiedMappedOutputs); LOGGER.error(message, modifiedOutputNameList); @@ -307,152 +254,120 @@ public class InterfaceOperationValidation { return Either.right(errorResponse); } - protected ResponseFormatManager getResponseFormatManager() { return ResponseFormatManager.getInstance(); } - private Either isInterfaceOperationTypeValid(Operation interfaceOperation, - ResponseFormatManager responseFormatManager, - InterfaceDefinition interfaceDefinition, - boolean isUpdate) { - - Either operationTypeEmptyEither = - isOperationTypeEmpty(responseFormatManager, interfaceOperation.getName()); + private Either isInterfaceOperationTypeValid(Operation interfaceOperation, ResponseFormatManager responseFormatManager, + InterfaceDefinition interfaceDefinition, boolean isUpdate) { + Either operationTypeEmptyEither = isOperationTypeEmpty(responseFormatManager, interfaceOperation.getName()); if (operationTypeEmptyEither.isRight()) { return Either.right(operationTypeEmptyEither.right().value()); } - - Either operationTypeRegexValidationResponse = - isOperationTypeRegexValid(responseFormatManager, interfaceOperation.getName()); + Either operationTypeRegexValidationResponse = isOperationTypeRegexValid(responseFormatManager, + interfaceOperation.getName()); if (operationTypeRegexValidationResponse.isRight()) { return Either.right(operationTypeRegexValidationResponse.right().value()); } - - Either operationTypeUniqueResponse = validateOperationTypeUnique(interfaceOperation, - interfaceDefinition, isUpdate); + Either operationTypeUniqueResponse = validateOperationTypeUnique(interfaceOperation, interfaceDefinition, isUpdate); if (operationTypeUniqueResponse.isRight()) { return Either.right(operationTypeUniqueResponse.right().value()); } if (!operationTypeUniqueResponse.left().value()) { LOGGER.error("Interface Operation type {} already in use ", interfaceOperation.getName()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat( - ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, interfaceOperation.getName()); + ResponseFormat errorResponse = responseFormatManager + .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, interfaceOperation.getName()); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either validateInputParameters(Operation interfaceOperation, - ResponseFormatManager responseFormatManager) { + private Either validateInputParameters(Operation interfaceOperation, ResponseFormatManager responseFormatManager) { if (isInputParameterNameEmpty(interfaceOperation)) { LOGGER.error("Interface operation input parameter name can't be empty"); - ResponseFormat inputResponse = - responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_MANDATORY); + ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_MANDATORY); return Either.right(inputResponse); } - - Either> validateInputParametersUniqueResponse = - isInputParametersUnique(interfaceOperation); + Either> validateInputParametersUniqueResponse = isInputParametersUnique(interfaceOperation); if (validateInputParametersUniqueResponse.isRight()) { - LOGGER.error("Interface operation input parameter names {} already in use", - validateInputParametersUniqueResponse.right().value()); - ResponseFormat inputResponse = - responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_ALREADY_IN_USE, - validateInputParametersUniqueResponse.right().value().toString()); + LOGGER.error("Interface operation input parameter names {} already in use", validateInputParametersUniqueResponse.right().value()); + ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_ALREADY_IN_USE, + validateInputParametersUniqueResponse.right().value().toString()); return Either.right(inputResponse); } return Either.left(Boolean.TRUE); } - private Either validateOutputParameters(Operation interfaceOperation, - ResponseFormatManager responseFormatManager) { + private Either validateOutputParameters(Operation interfaceOperation, ResponseFormatManager responseFormatManager) { if (isOutputParameterNameEmpty(interfaceOperation)) { LOGGER.error("Interface operation output parameter name can't be empty"); - ResponseFormat inputResponse = - responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY); + ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY); return Either.right(inputResponse); } - - Either> validateOutputParametersUniqueResponse = - isOutputParametersUnique(interfaceOperation); + Either> validateOutputParametersUniqueResponse = isOutputParametersUnique(interfaceOperation); if (validateOutputParametersUniqueResponse.isRight()) { - LOGGER.error("Interface operation output parameter names {} already in use", - validateOutputParametersUniqueResponse.right().value()); - ResponseFormat inputResponse = - responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE, - validateOutputParametersUniqueResponse.right().value().toString()); + LOGGER.error("Interface operation output parameter names {} already in use", validateOutputParametersUniqueResponse.right().value()); + ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE, + validateOutputParametersUniqueResponse.right().value().toString()); return Either.right(inputResponse); } return Either.left(Boolean.TRUE); } - private Either isOperationTypeEmpty(ResponseFormatManager responseFormatManager, - String operationType) { + private Either isOperationTypeEmpty(ResponseFormatManager responseFormatManager, String operationType) { if (StringUtils.isEmpty(operationType)) { LOGGER.error("Interface Operation type is mandatory"); - ResponseFormat errorResponse = - responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_MANDATORY); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_MANDATORY); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either isOperationTypeRegexValid(ResponseFormatManager responseFormatManager, - String operationType) { + private Either isOperationTypeRegexValid(ResponseFormatManager responseFormatManager, String operationType) { if (!isValidOperationType(operationType)) { LOGGER.error("Interface Operation type {} is invalid, Operation type should not contain" - + "Special character, space, numbers and should not be greater than 200 characters", - operationType); - ResponseFormat errorResponse = responseFormatManager - .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_INVALID, - operationType); + + "Special character, space, numbers and should not be greater than 200 characters", operationType); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_INVALID, operationType); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either validateOperationTypeUnique(Operation interfaceOperation, - InterfaceDefinition interfaceDefinition, boolean isUpdate) { + private Either validateOperationTypeUnique(Operation interfaceOperation, InterfaceDefinition interfaceDefinition, + boolean isUpdate) { boolean isOperationTypeUnique = false; - if (interfaceDefinition == null || CollectionUtils.isEmpty(interfaceDefinition.getOperationsMap().values())) { return Either.left(true); } - Map operationTypes = new HashMap<>(); interfaceDefinition.getOperationsMap().values() - .forEach(operationType -> operationTypes.put(operationType.getUniqueId(), operationType.getName())); - + .forEach(operationType -> operationTypes.put(operationType.getUniqueId(), operationType.getName())); if (!operationTypes.values().contains(interfaceOperation.getName())) { isOperationTypeUnique = true; } if (!isOperationTypeUnique && isUpdate) { - Optional id = operationTypes.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), - interfaceOperation.getName())).map(Map.Entry::getKey).findAny(); + Optional id = operationTypes.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), interfaceOperation.getName())) + .map(Map.Entry::getKey).findAny(); if (id.isPresent() && id.get().equalsIgnoreCase(interfaceOperation.getUniqueId())) { isOperationTypeUnique = true; } } - return Either.left(isOperationTypeUnique); } private Boolean isInputParameterNameEmpty(Operation operationDataDefinition) { - return operationDataDefinition.getInputs().getListToscaDataDefinition().stream().anyMatch( - inputParam -> inputParam.getName() == null || inputParam.getName().trim().equals(StringUtils.EMPTY)); + return operationDataDefinition.getInputs().getListToscaDataDefinition().stream() + .anyMatch(inputParam -> inputParam.getName() == null || inputParam.getName().trim().equals(StringUtils.EMPTY)); } - private Either> isInputParametersUnique(Operation operationDataDefinition) { Set inputParamNamesSet = new HashSet<>(); Set duplicateParamNamesToReturn = new HashSet<>(); - operationDataDefinition.getInputs().getListToscaDataDefinition() - .forEach(inputParam -> { - if (!inputParamNamesSet.add(inputParam.getName().trim())) { - duplicateParamNamesToReturn.add(inputParam.getName().trim()); - } - }); + operationDataDefinition.getInputs().getListToscaDataDefinition().forEach(inputParam -> { + if (!inputParamNamesSet.add(inputParam.getName().trim())) { + duplicateParamNamesToReturn.add(inputParam.getName().trim()); + } + }); if (!duplicateParamNamesToReturn.isEmpty()) { return Either.right(duplicateParamNamesToReturn); } @@ -460,89 +375,80 @@ public class InterfaceOperationValidation { } private Boolean isOutputParameterNameEmpty(Operation operationDataDefinition) { - return operationDataDefinition.getOutputs().getListToscaDataDefinition().stream().anyMatch( - outputParam -> outputParam.getName() == null || outputParam.getName().trim().equals(StringUtils.EMPTY)); + return operationDataDefinition.getOutputs().getListToscaDataDefinition().stream() + .anyMatch(outputParam -> outputParam.getName() == null || outputParam.getName().trim().equals(StringUtils.EMPTY)); } private Either> isOutputParametersUnique(Operation operationDataDefinition) { Set outputParamNamesSet = new HashSet<>(); Set duplicateParamNamesToReturn = new HashSet<>(); - operationDataDefinition.getOutputs().getListToscaDataDefinition() - .forEach(outputParam -> { - if (!outputParamNamesSet.add(outputParam.getName().trim())) { - duplicateParamNamesToReturn.add(outputParam.getName().trim()); - } - }); + operationDataDefinition.getOutputs().getListToscaDataDefinition().forEach(outputParam -> { + if (!outputParamNamesSet.add(outputParam.getName().trim())) { + duplicateParamNamesToReturn.add(outputParam.getName().trim()); + } + }); if (!duplicateParamNamesToReturn.isEmpty()) { return Either.right(duplicateParamNamesToReturn); } return Either.left(Boolean.TRUE); } - private Either validateInputPropertyExistInComponent(Operation operation, - InterfaceDefinition inputInterfaceDefinition, org.openecomp.sdc.be.model.Component component, - ResponseFormatManager responseFormatManager) { - + private Either validateInputPropertyExistInComponent(Operation operation, InterfaceDefinition inputInterfaceDefinition, + org.openecomp.sdc.be.model.Component component, + ResponseFormatManager responseFormatManager) { boolean isOperationInputToInputPropertyMappingValid = false; boolean isOperationInputToOtherOperationOutputMappingValid = false; String mappingName = ""; - List inputListToscaDataDefinition = - operation.getInputs().getListToscaDataDefinition(); + List inputListToscaDataDefinition = operation.getInputs().getListToscaDataDefinition(); for (OperationInputDefinition inputDefinition : inputListToscaDataDefinition) { - if (isOperationInputMappedToComponentInput(inputDefinition, component.getInputs()) - || isCapabilityProperty(inputDefinition.getInputId(), component).isPresent()) { + if (isOperationInputMappedToComponentInput(inputDefinition, component.getInputs()) || isCapabilityProperty(inputDefinition.getInputId(), + component).isPresent()) { isOperationInputToInputPropertyMappingValid = true; } else { - mappingName = inputDefinition.getInputId().contains(".") - ? inputDefinition.getInputId().substring(inputDefinition.getInputId().lastIndexOf('.') + 1) - : inputDefinition.getInputId(); + mappingName = inputDefinition.getInputId().contains(".") ? inputDefinition.getInputId() + .substring(inputDefinition.getInputId().lastIndexOf('.') + 1) : inputDefinition.getInputId(); break; } } if (isOperationInputToInputPropertyMappingValid) { return Either.left(Boolean.TRUE); } - //Mapped property not found in the component properties.. Check in other operation output parameters of + // component (other operation => not having the same full name) String actualOperationIdentifier = inputInterfaceDefinition.getType() + "." + operation.getName(); - ListDataDefinition outputListDataDefinition = - getOtherOperationOutputsOfComponent(actualOperationIdentifier, component.getInterfaces()); - - List componentOutputsFromOtherOperations = - outputListDataDefinition.getListToscaDataDefinition(); + ListDataDefinition outputListDataDefinition = getOtherOperationOutputsOfComponent(actualOperationIdentifier, + component.getInterfaces()); + List componentOutputsFromOtherOperations = outputListDataDefinition.getListToscaDataDefinition(); if (validateOutputExistsInComponent(mappingName, componentOutputsFromOtherOperations)) { isOperationInputToOtherOperationOutputMappingValid = true; } else { //Get the output parameter display name from the full name mappingName = getOperationOutputName(mappingName); } - if (!isOperationInputToOtherOperationOutputMappingValid) { LOGGER.error("Interface operation input parameter property {} not found in component input properties or" - + "capability properties or outputs of other operations.", mappingName); + + "capability properties or outputs of other operations.", mappingName); ResponseFormat inputResponse = responseFormatManager - .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT, - mappingName, component.getComponentType().getValue()); + .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT, mappingName, + component.getComponentType().getValue()); return Either.right(inputResponse); } return Either.left(Boolean.TRUE); } - private boolean validateOutputExistsInComponent(String mappedOutputName, - List outputs) { - return outputs.stream() - .anyMatch(output -> output.getName().equals(mappedOutputName)); + private boolean validateOutputExistsInComponent(String mappedOutputName, List outputs) { + return outputs.stream().anyMatch(output -> output.getName().equals(mappedOutputName)); } /** * Get the input definitions of other operations of the component from current as well as other interfaces. + * * @param currentOperationIdentifier Identifier for the request operation (interface_name.operation_name) - * @param componentInterfaces Interfaces of the component + * @param componentInterfaces Interfaces of the component */ private List getOtherOperationInputsOfComponent(String currentOperationIdentifier, - Map - componentInterfaces) { + Map componentInterfaces) { List otherOperationInputs = new ArrayList<>(); if (MapUtils.isEmpty(componentInterfaces)) { return otherOperationInputs; @@ -554,8 +460,7 @@ public class InterfaceOperationValidation { } for (Map.Entry operationEntry : operations.entrySet()) { ListDataDefinition inputs = operationEntry.getValue().getInputs(); - String expectedOperationIdentifier = - interfaceDefinitionEntry.getValue().getType() + "." + operationEntry.getValue().getName(); + String expectedOperationIdentifier = interfaceDefinitionEntry.getValue().getType() + "." + operationEntry.getValue().getName(); if (!currentOperationIdentifier.equals(expectedOperationIdentifier) && Objects.nonNull(inputs) && !inputs.isEmpty()) { otherOperationInputs.addAll(inputs.getListToscaDataDefinition()); } @@ -566,12 +471,12 @@ public class InterfaceOperationValidation { /** * Get the output of an operation in an interface. - * @param inputOperationId Unique identifier for the request operation + * + * @param inputOperationId Unique identifier for the request operation * @param componentInterfaces Interfaces of the component */ private List getInterfaceOperationOutputs(String inputOperationId, - Map - componentInterfaces) { + Map componentInterfaces) { List operationOutputDefinitions = new ArrayList<>(); if (MapUtils.isEmpty(componentInterfaces)) { return operationOutputDefinitions; @@ -584,11 +489,9 @@ public class InterfaceOperationValidation { for (Map.Entry operationEntry : operations.entrySet()) { String expectedOperationId = operationEntry.getValue().getUniqueId(); if (expectedOperationId.equals(inputOperationId)) { - ListDataDefinition operationOutputs = - operationEntry.getValue().getOutputs(); - return (Objects.isNull(operationOutputs) || operationOutputs.isEmpty()) - ? operationOutputDefinitions - : operationOutputs.getListToscaDataDefinition(); + ListDataDefinition operationOutputs = operationEntry.getValue().getOutputs(); + return (Objects.isNull(operationOutputs) || operationOutputs.isEmpty()) ? operationOutputDefinitions + : operationOutputs.getListToscaDataDefinition(); } } } @@ -598,5 +501,4 @@ public class InterfaceOperationValidation { private boolean isValidOperationType(String operationType) { return Pattern.matches(TYPE_VALIDATION_REGEX, operationType); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java index 8c27396e3b..6bfe26aab0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; import com.google.common.collect.ImmutableSet; @@ -55,34 +54,28 @@ import org.springframework.util.CollectionUtils; public class NodeFilterValidator { private static final String SOURCE = "Source"; - public static final Set comparableTypes = ImmutableSet.of(ToscaPropertyType.STRING.getType(), - ToscaPropertyType.INTEGER.getType(), ToscaPropertyType.FLOAT.getType()); - public static final Set schemableTypes = - ImmutableSet.of(ToscaPropertyType.MAP.getType(), ToscaPropertyType.LIST.getType()); - public static final Set comparableConstraintsOperators = - ImmutableSet.of(ConstraintConvertor.GREATER_THAN_OPERATOR, ConstraintConvertor.LESS_THAN_OPERATOR); - + public static final Set comparableTypes = ImmutableSet + .of(ToscaPropertyType.STRING.getType(), ToscaPropertyType.INTEGER.getType(), ToscaPropertyType.FLOAT.getType()); + public static final Set schemableTypes = ImmutableSet.of(ToscaPropertyType.MAP.getType(), ToscaPropertyType.LIST.getType()); + public static final Set comparableConstraintsOperators = ImmutableSet + .of(ConstraintConvertor.GREATER_THAN_OPERATOR, ConstraintConvertor.LESS_THAN_OPERATOR); protected final ToscaOperationFacade toscaOperationFacade; protected final ComponentsUtils componentsUtils; - private static final Logger LOGGER = LoggerFactory.getLogger(NodeFilterValidator.class); @Autowired - public NodeFilterValidator(final ToscaOperationFacade toscaOperationFacade, - final ComponentsUtils componentsUtils) { + public NodeFilterValidator(final ToscaOperationFacade toscaOperationFacade, final ComponentsUtils componentsUtils) { this.toscaOperationFacade = toscaOperationFacade; this.componentsUtils = componentsUtils; } - public Either validateComponentInstanceExist(final Component component, - final String componentInstanceId) { + public Either validateComponentInstanceExist(final Component component, final String componentInstanceId) { if (component == null || StringUtils.isEmpty(componentInstanceId)) { LOGGER.error("Input data cannot be empty"); return getErrorResponse(ActionStatus.FILTER_NOT_FOUND); } - if (CollectionUtils.isEmpty(component.getComponentInstances()) || - component.getComponentInstances().stream() - .noneMatch(ci -> ci.getUniqueId().equals(componentInstanceId))) { + if (CollectionUtils.isEmpty(component.getComponentInstances()) || component.getComponentInstances().stream() + .noneMatch(ci -> ci.getUniqueId().equals(componentInstanceId))) { LOGGER.error("Component Instance list is empty"); return getErrorResponse(ActionStatus.FILTER_NOT_FOUND); } @@ -94,31 +87,26 @@ public class NodeFilterValidator { return Either.right(errorResponse); } - public Either validateFilter(final Component parentComponent, - final String componentInstanceId, - final List uiConstraints, - final NodeFilterConstraintAction action, + public Either validateFilter(final Component parentComponent, final String componentInstanceId, + final List uiConstraints, final NodeFilterConstraintAction action, final NodeFilterConstraintType nodeFilterConstraintType) { try { if (NodeFilterConstraintAction.ADD == action || NodeFilterConstraintAction.UPDATE == action) { for (final String uiConstraint : uiConstraints) { final UIConstraint constraint = new ConstraintConvertor().convert(uiConstraint); if (ConstraintConvertor.PROPERTY_CONSTRAINT.equals(constraint.getSourceType())) { - final Either booleanResponseFormatEither = - validatePropertyConstraint(parentComponent, componentInstanceId, constraint); + final Either booleanResponseFormatEither = validatePropertyConstraint(parentComponent, + componentInstanceId, constraint); if (booleanResponseFormatEither.isRight()) { return booleanResponseFormatEither; } } else if (ConstraintConvertor.STATIC_CONSTRAINT.equals(constraint.getSourceType())) { Either booleanResponseFormatEither; if (NodeFilterConstraintType.PROPERTIES.equals(nodeFilterConstraintType)) { - booleanResponseFormatEither = isComponentPropertyFilterValid( - parentComponent, componentInstanceId, constraint); + booleanResponseFormatEither = isComponentPropertyFilterValid(parentComponent, componentInstanceId, constraint); } else { - booleanResponseFormatEither = isComponentCapabilityPropertyFilterValid( - parentComponent, componentInstanceId, constraint); + booleanResponseFormatEither = isComponentCapabilityPropertyFilterValid(parentComponent, componentInstanceId, constraint); } - if (booleanResponseFormatEither.isRight()) { return booleanResponseFormatEither; } @@ -129,75 +117,49 @@ public class NodeFilterValidator { LOGGER.debug("Provided constraint" + uiConstraints, e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.CONSTRAINT_FORMAT_INCORRECT)); } - return Either.left(true); } private Either isComponentCapabilityPropertyFilterValid(final Component parentComponent, final String componentInstanceId, final UIConstraint uiConstraint) { - return validateStaticValueAndOperatorOfCapabilityProperties(parentComponent, componentInstanceId, uiConstraint); - } - private Either isComponentPropertyFilterValid(Component parentComponent, - String componentInstanceId, + private Either isComponentPropertyFilterValid(Component parentComponent, String componentInstanceId, UIConstraint constraint) { - return validateStaticValueAndOperator(parentComponent, componentInstanceId, constraint); } - private Either validatePropertyConstraint(final Component parentComponent, - final String componentInstanceId, + private Either validatePropertyConstraint(final Component parentComponent, final String componentInstanceId, final UIConstraint uiConstraint) { String source = SOURCE; final Optional optionalComponentInstance; - final List propertyDefinitions = parentComponent.getProperties(); List sourcePropertyDefinition = - parentComponent.getName().equals(uiConstraint.getSourceName()) && - propertyDefinitions != null ? propertyDefinitions : Collections.emptyList(); - + parentComponent.getName().equals(uiConstraint.getSourceName()) && propertyDefinitions != null ? propertyDefinitions + : Collections.emptyList(); if (sourcePropertyDefinition.isEmpty() && !parentComponent.getName().equals(uiConstraint.getSourceName())) { optionalComponentInstance = parentComponent.getComponentInstances().stream() - .filter(componentInstance -> uiConstraint.getSourceName() - .equals(componentInstance - .getName())) - .findFirst(); - + .filter(componentInstance -> uiConstraint.getSourceName().equals(componentInstance.getName())).findFirst(); if (optionalComponentInstance.isPresent()) { - final List componentInstanceProperties = - parentComponent.getComponentInstancesProperties() - .get(optionalComponentInstance.get().getUniqueId()); - sourcePropertyDefinition = - componentInstanceProperties == null ? new ArrayList<>() : componentInstanceProperties; + final List componentInstanceProperties = parentComponent.getComponentInstancesProperties() + .get(optionalComponentInstance.get().getUniqueId()); + sourcePropertyDefinition = componentInstanceProperties == null ? new ArrayList<>() : componentInstanceProperties; } } - if (!CollectionUtils.isEmpty(sourcePropertyDefinition)) { final Optional sourceSelectedProperty = sourcePropertyDefinition.stream() - .filter(property -> uiConstraint - .getValue() - .equals(property.getName())) - .findFirst(); - - final Optional targetComponentInstanceProperty = - parentComponent.getComponentInstancesProperties().get(componentInstanceId).stream() - .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())) - .findFirst(); - + .filter(property -> uiConstraint.getValue().equals(property.getName())).findFirst(); + final Optional targetComponentInstanceProperty = parentComponent.getComponentInstancesProperties() + .get(componentInstanceId).stream().filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())).findFirst(); source = !targetComponentInstanceProperty.isPresent() ? "Target" : SOURCE; if (sourceSelectedProperty.isPresent() && targetComponentInstanceProperty.isPresent()) { return validatePropertyData(uiConstraint, sourceSelectedProperty, targetComponentInstanceProperty); } } - - final String missingProperty = - source.equals(SOURCE) ? uiConstraint.getValue().toString() : uiConstraint.getServicePropertyName(); - - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.MAPPED_PROPERTY_NOT_FOUND, source, missingProperty)); + final String missingProperty = source.equals(SOURCE) ? uiConstraint.getValue().toString() : uiConstraint.getServicePropertyName(); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MAPPED_PROPERTY_NOT_FOUND, source, missingProperty)); } private Either validatePropertyData(UIConstraint uiConstraint, @@ -213,122 +175,105 @@ public class NodeFilterValidator { final SchemaDefinition sourceSchemaDefinition = sourcePropDefinition.getSchema(); final SchemaDefinition targetSchemaDefinition = targetPropDefinition.getSchema(); if (!sourceSchemaDefinition.equals(targetSchemaDefinition)) { - return Either - .right(componentsUtils.getResponseFormat(ActionStatus.SOURCE_TARGET_SCHEMA_MISMATCH, - uiConstraint.getServicePropertyName(), uiConstraint.getValue().toString())); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.SOURCE_TARGET_SCHEMA_MISMATCH, uiConstraint.getServicePropertyName(), + uiConstraint.getValue().toString())); } } return Either.left(Boolean.TRUE); } else { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.SOURCE_TARGET_PROPERTY_TYPE_MISMATCH, - uiConstraint.getServicePropertyName(), uiConstraint.getValue().toString())); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.SOURCE_TARGET_PROPERTY_TYPE_MISMATCH, uiConstraint.getServicePropertyName(), + uiConstraint.getValue().toString())); } } else { - LOGGER.debug( - "Null value passed to `validatePropertyData` - sourceSelectedProperty: '{}' - targetComponentInstanceProperty: '{}'", + LOGGER.debug("Null value passed to `validatePropertyData` - sourceSelectedProperty: '{}' - targetComponentInstanceProperty: '{}'", sourceSelectedProperty, targetComponentInstanceProperty); return Either.right(componentsUtils - .getResponseFormat(ActionStatus.GENERAL_ERROR, uiConstraint.getServicePropertyName(), - uiConstraint.getValue().toString())); + .getResponseFormat(ActionStatus.GENERAL_ERROR, uiConstraint.getServicePropertyName(), uiConstraint.getValue().toString())); } } - private Either validateStaticValueAndOperator( - final Component parentComponent, - final String componentInstanceId, final UIConstraint uiConstraint) { + private Either validateStaticValueAndOperator(final Component parentComponent, final String componentInstanceId, + final UIConstraint uiConstraint) { if (!(Objects.nonNull(uiConstraint) && uiConstraint.getValue() instanceof String)) { return Either.left(false); } //TODO: get capabilities properties when constraint type is capabilities - final Optional componentInstanceProperty = - parentComponent.getComponentInstancesProperties().get(componentInstanceId).stream() - .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())) - .findFirst(); - + final Optional componentInstanceProperty = parentComponent.getComponentInstancesProperties() + .get(componentInstanceId).stream().filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())).findFirst(); if (!componentInstanceProperty.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, - uiConstraint.getServicePropertyName())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, uiConstraint.getServicePropertyName())); } - if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes.contains( - componentInstanceProperty.get().getType())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, - uiConstraint.getServicePropertyName(), uiConstraint.getConstraintOperator())); + if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes + .contains(componentInstanceProperty.get().getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, uiConstraint.getServicePropertyName(), + uiConstraint.getConstraintOperator())); } - return isValidValueCheck(componentInstanceProperty.get().getType(), String.valueOf(uiConstraint.getValue()), uiConstraint.getServicePropertyName()); } - private Either validateStaticValueAndOperatorOfCapabilityProperties( - final Component parentComponent, final String componentInstanceId, final UIConstraint uiConstraint) { + private Either validateStaticValueAndOperatorOfCapabilityProperties(final Component parentComponent, + final String componentInstanceId, + final UIConstraint uiConstraint) { if (!(Objects.nonNull(uiConstraint) && uiConstraint.getValue() instanceof String)) { return Either.left(false); } Optional optionalComponentInstanceProperty = Optional.empty(); final Optional optionalComponentInstances = parentComponent.getComponentInstances().stream() - .filter(componentInstance -> componentInstanceId.equalsIgnoreCase(componentInstance.getUniqueId())) - .findFirst(); + .filter(componentInstance -> componentInstanceId.equalsIgnoreCase(componentInstance.getUniqueId())).findFirst(); if (optionalComponentInstances.isPresent()) { - final Optional> optionalCapabilityDefinitionList = optionalComponentInstances.get() - .getCapabilities().values().stream() - .filter(capabilityDefinitions -> capabilityDefinitions - .stream().allMatch(capabilityDefinition -> capabilityDefinition.getProperties() != null)) - .collect(Collectors.toList()) - .stream().filter(capabilityDefinitions -> capabilityDefinitions.stream().allMatch( - capabilityDefinition -> capabilityDefinition.getProperties().stream().anyMatch( - componentInstanceProperty -> uiConstraint.getServicePropertyName() - .equalsIgnoreCase(componentInstanceProperty.getName())))).findFirst(); - + final Optional> optionalCapabilityDefinitionList = optionalComponentInstances.get().getCapabilities().values() + .stream().filter(capabilityDefinitions -> capabilityDefinitions.stream() + .allMatch(capabilityDefinition -> capabilityDefinition.getProperties() != null)).collect(Collectors.toList()).stream().filter( + capabilityDefinitions -> capabilityDefinitions.stream().allMatch( + capabilityDefinition -> capabilityDefinition.getProperties().stream().anyMatch( + componentInstanceProperty -> uiConstraint.getServicePropertyName() + .equalsIgnoreCase(componentInstanceProperty.getName())))).findFirst(); if (optionalCapabilityDefinitionList.isPresent()) { optionalComponentInstanceProperty = optionalCapabilityDefinitionList.get().stream().findAny() .map(capabilityDefinition -> capabilityDefinition.getProperties().get(0)); } } - if (optionalComponentInstanceProperty.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, - uiConstraint.getServicePropertyName())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, uiConstraint.getServicePropertyName())); } - if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes.contains( - optionalComponentInstanceProperty.get().getType())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, - uiConstraint.getServicePropertyName(), uiConstraint.getConstraintOperator())); + if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes + .contains(optionalComponentInstanceProperty.get().getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, uiConstraint.getServicePropertyName(), + uiConstraint.getConstraintOperator())); } - return isValidValueCheck(optionalComponentInstanceProperty.get().getType(), String.valueOf(uiConstraint.getValue()), uiConstraint.getServicePropertyName()); } private Either isValidValueCheck(String type, String value, String propertyName) { - ToscaPropertyType toscaPropertyType = ToscaPropertyType.isValidType(type); if (Objects.isNull(toscaPropertyType)) { - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_PROPERTY_TYPE, type, propertyName)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_PROPERTY_TYPE, type, propertyName)); } if (toscaPropertyType.getValidator().isValid(value, null)) { return Either.left(Boolean.TRUE); } - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_VALUE_PROVIDED, type, propertyName, value)); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_VALUE_PROVIDED, type, propertyName, value)); } - public Either validateComponentFilter(final Component component, - final List uiConstraints, + public Either validateComponentFilter(final Component component, final List uiConstraints, final NodeFilterConstraintAction action) { try { if (NodeFilterConstraintAction.ADD == action || NodeFilterConstraintAction.UPDATE == action) { for (final String uiConstraint : uiConstraints) { final UIConstraint constraint = new ConstraintConvertor().convert(uiConstraint); if (ConstraintConvertor.PROPERTY_CONSTRAINT.equals(constraint.getSourceType())) { - final Either booleanResponseFormatEither = - validateComponentPropertyConstraint(component, constraint); + final Either booleanResponseFormatEither = validateComponentPropertyConstraint(component, + constraint); if (booleanResponseFormatEither.isRight()) { return booleanResponseFormatEither; } } else if (ConstraintConvertor.STATIC_CONSTRAINT.equals(constraint.getSourceType())) { - final Either booleanResponseFormatEither = - validateComponentStaticValueAndOperator(component, constraint); + final Either booleanResponseFormatEither = validateComponentStaticValueAndOperator(component, + constraint); if (booleanResponseFormatEither.isRight()) { return booleanResponseFormatEither; } @@ -339,66 +284,42 @@ public class NodeFilterValidator { LOGGER.debug("Provided constraint" + uiConstraints, e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.CONSTRAINT_FORMAT_INCORRECT)); } - return Either.left(true); } - private Either validateComponentPropertyConstraint(final Component component, - final UIConstraint uiConstraint) { + private Either validateComponentPropertyConstraint(final Component component, final UIConstraint uiConstraint) { String source = SOURCE; - final List propertyDefinitions = component.getProperties(); List sourcePropertyDefinition = - component.getName().equals(uiConstraint.getSourceName()) && - propertyDefinitions != null ? propertyDefinitions : Collections.emptyList(); - + component.getName().equals(uiConstraint.getSourceName()) && propertyDefinitions != null ? propertyDefinitions : Collections.emptyList(); if (!CollectionUtils.isEmpty(sourcePropertyDefinition)) { final Optional sourceSelectedProperty = sourcePropertyDefinition.stream() - .filter(property -> uiConstraint - .getValue() - .equals(property.getName())) - .findFirst(); - - final Optional targetComponentProperty = - component.getProperties().stream() - .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())) - .findFirst(); - + .filter(property -> uiConstraint.getValue().equals(property.getName())).findFirst(); + final Optional targetComponentProperty = component.getProperties().stream() + .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())).findFirst(); source = !targetComponentProperty.isPresent() ? "Target" : SOURCE; if (sourceSelectedProperty.isPresent() && targetComponentProperty.isPresent()) { return validatePropertyData(uiConstraint, sourceSelectedProperty, targetComponentProperty); } } - - final String missingProperty = - source.equals(SOURCE) ? uiConstraint.getValue().toString() : uiConstraint.getServicePropertyName(); - - return Either.right( - componentsUtils.getResponseFormat(ActionStatus.MAPPED_PROPERTY_NOT_FOUND, source, missingProperty)); + final String missingProperty = source.equals(SOURCE) ? uiConstraint.getValue().toString() : uiConstraint.getServicePropertyName(); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MAPPED_PROPERTY_NOT_FOUND, source, missingProperty)); } - private Either validateComponentStaticValueAndOperator( - final Component component, final UIConstraint uiConstraint) { + private Either validateComponentStaticValueAndOperator(final Component component, final UIConstraint uiConstraint) { if (!(Objects.nonNull(uiConstraint) && uiConstraint.getValue() instanceof String)) { return Either.left(false); } - final Optional componentProperty = - component.getProperties().stream() - .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())) - .findFirst(); - + final Optional componentProperty = component.getProperties().stream() + .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())).findFirst(); if (componentProperty.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, - uiConstraint.getServicePropertyName())); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, uiConstraint.getServicePropertyName())); } - if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes.contains( - componentProperty.get().getType())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, - uiConstraint.getServicePropertyName(), uiConstraint.getConstraintOperator())); + if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes + .contains(componentProperty.get().getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, uiConstraint.getServicePropertyName(), + uiConstraint.getConstraintOperator())); } - - return isValidValueCheck(componentProperty.get().getType(), String.valueOf(uiConstraint.getValue()), - uiConstraint.getServicePropertyName()); + return isValidValueCheck(componentProperty.get().getType(), String.valueOf(uiConstraint.getValue()), uiConstraint.getServicePropertyName()); } - } 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 index 7947cbc292..b1bc10b10a 100644 --- 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 @@ -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. @@ -17,10 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; +import static org.apache.commons.collections.MapUtils.isEmpty; +import static org.apache.commons.collections.MapUtils.isNotEmpty; +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; +import static org.openecomp.sdc.common.api.Constants.GROUP_POLICY_NAME_DELIMETER; + import fj.data.Either; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -34,17 +43,6 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; -import java.util.Collections; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -import static org.apache.commons.collections.MapUtils.isEmpty; -import static org.apache.commons.collections.MapUtils.isNotEmpty; -import static org.apache.commons.lang3.StringUtils.isEmpty; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; -import static org.openecomp.sdc.common.api.Constants.GROUP_POLICY_NAME_DELIMETER; - /** * Provides specific functionality for policy */ @@ -65,16 +63,10 @@ public class PolicyUtils { public static int getNextPolicyCounter(Map policies) { int nextCounter = 0; if (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); + 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; @@ -88,7 +80,8 @@ public class PolicyUtils { * @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) { + public static Either validatePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, + Map policies) { validateImmutablePolicyFields(recievedPolicy, validPolicy); return validateUpdateMutablePolicyFields(recievedPolicy, validPolicy, policies); } @@ -99,28 +92,21 @@ public class PolicyUtils { * @return the set of the policies */ public static Set getExcludedPolicyTypesByComponent(Component component) { - if (isEmpty(ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getExcludedPolicyTypesMapping())) { + if (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(component.getComponentType().name()); } - return ConfigurationManager.getConfigurationManager() - .getConfiguration() - .getExcludedPolicyTypesMapping() - .get(((Resource) component).getResourceType().getValue()); + return ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping() + .get(((Resource) component).getResourceType().getValue()); } public static PolicyDefinition getDeclaredPolicyDefinition(String componentInstanceId, ComponentInstanceProperty property) { PolicyDefinition policyDefinition = new PolicyDefinition(property); policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentInstanceId, property.getName())); policyDefinition.setInstanceUniqueId(componentInstanceId); - return policyDefinition; } @@ -146,14 +132,15 @@ public class PolicyUtils { int beginIndex = policyName.lastIndexOf(GROUP_POLICY_NAME_DELIMETER) + GROUP_POLICY_NAME_DELIMETER.length(); String counterStr = policyName.substring(beginIndex, endIndex); counter = Integer.valueOf(counterStr) + 1; - } - catch (NumberFormatException | IndexOutOfBoundsException e) { + } catch (NumberFormatException | IndexOutOfBoundsException e) { log.error("#extractNextPolicyCounter - An error occurred when attempting to extract counter from policy name [{}]. ", policyName, e); } return counter; } - private static Either validateUpdateMutablePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map policies) { + private static Either validateUpdateMutablePolicyFields(PolicyDefinition recievedPolicy, + PolicyDefinition validPolicy, + Map policies) { return validateUpdatePolicyName(recievedPolicy, validPolicy, policies); } @@ -168,15 +155,15 @@ public class PolicyUtils { logImmutableFieldUpdateWarning(receivedPolicy.getPolicyTypeUid(), validPolicy.getPolicyTypeUid(), JsonPresentationFields.TYPE_UNIQUE_ID); logImmutableFieldUpdateWarning(receivedPolicy.getPolicyUUID(), validPolicy.getPolicyUUID(), JsonPresentationFields.UUID); logImmutableFieldUpdateWarning(receivedPolicy.getVersion(), validPolicy.getVersion(), JsonPresentationFields.VERSION); - logImmutableFieldUpdateWarning(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar().toString(), JsonPresentationFields.IS_FROM_CSAR); + logImmutableFieldUpdateWarning(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar().toString(), + JsonPresentationFields.IS_FROM_CSAR); } private static boolean isUpdatedField(String oldField, String newField) { boolean isUpdatedField = false; if (isEmpty(oldField) && isNotEmpty(newField)) { isUpdatedField = true; - } - else if (isNotEmpty(oldField) && isNotEmpty(newField) && !oldField.equals(newField)) { + } else if (isNotEmpty(oldField) && isNotEmpty(newField) && !oldField.equals(newField)) { isUpdatedField = true; } return isUpdatedField; @@ -184,27 +171,28 @@ public class PolicyUtils { private static void logImmutableFieldUpdateWarning(String oldValue, String newValue, JsonPresentationFields field) { if (isUpdatedField(oldValue, newValue)) { - log.warn("#logImmutableFieldUpdateWarning - 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); + log.warn( + "#logImmutableFieldUpdateWarning - 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) { + private static Either validateUpdatePolicyName(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy, + Map policies) { Either result = null; Optional sameNamePolicy = Optional.empty(); - if (isEmpty(receivedPolicy.getName()) || !ValidationUtils.POLICY_NAME_PATTERN.matcher(receivedPolicy - .getName()).matches()) { - log.error("#validateUpdatePolicyName - Failed to validate the name {} of the policy {}. ", receivedPolicy.getName(), receivedPolicy.getUniqueId()); + if (isEmpty(receivedPolicy.getName()) || !ValidationUtils.POLICY_NAME_PATTERN.matcher(receivedPolicy.getName()).matches()) { + log.error("#validateUpdatePolicyName - Failed to validate the name {} of the policy {}. ", receivedPolicy.getName(), + receivedPolicy.getUniqueId()); result = Either.right(ActionStatus.INVALID_POLICY_NAME); } if (result == null && isNotEmpty(policies)) { - sameNamePolicy = policies.values() - .stream() - .filter(p -> p.getName().equals(receivedPolicy.getName())) - .findFirst(); + sameNamePolicy = policies.values().stream().filter(p -> p.getName().equals(receivedPolicy.getName())).findFirst(); } if (sameNamePolicy.isPresent()) { - log.error("#validateUpdatePolicyName - Failed to validate the name {} of the policy {}. The policy {} with the same name already exists. ", receivedPolicy - .getName(), receivedPolicy.getUniqueId(), sameNamePolicy.get().getUniqueId()); + log.error( + "#validateUpdatePolicyName - 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) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.java index ecbb039fa3..bdb6799cb6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.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. @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; @@ -39,10 +41,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Map; -import java.util.Optional; - @Component public class PropertyValidator { @@ -52,94 +50,84 @@ public class PropertyValidator { private final ExceptionUtils exceptionUtils; private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class); - public PropertyValidator(PropertyOperation propertyOperation, ComponentsUtils componentsUtils, - ApplicationDataTypeCache applicationDataTypeCache, ExceptionUtils exceptionUtils) { + public PropertyValidator(PropertyOperation propertyOperation, ComponentsUtils componentsUtils, ApplicationDataTypeCache applicationDataTypeCache, + ExceptionUtils exceptionUtils) { this.exceptionUtils = exceptionUtils; this.propertyOperation = propertyOperation; this.componentsUtils = componentsUtils; this.applicationDataTypeCache = applicationDataTypeCache; } - public void thinPropertiesValidator(List properties, - List dbAnnotationTypeDefinitionProperties, - Map allDataTypes){ + public void thinPropertiesValidator(List properties, List dbAnnotationTypeDefinitionProperties, + Map allDataTypes) { for (PropertyDefinition property : properties) { - PropertyDefinition annotationTypeSpecificProperty = isPropertyInsideAnnotationTypeProperties( - dbAnnotationTypeDefinitionProperties, property); - if(annotationTypeSpecificProperty!=null){ + PropertyDefinition annotationTypeSpecificProperty = isPropertyInsideAnnotationTypeProperties(dbAnnotationTypeDefinitionProperties, + property); + if (annotationTypeSpecificProperty != null) { verifyPropertyIsOfDefinedType(property, annotationTypeSpecificProperty, allDataTypes); } } } - private void verifyPropertyIsOfDefinedType(PropertyDefinition property, - PropertyDefinition typeSpecificProperty, + private void verifyPropertyIsOfDefinedType(PropertyDefinition property, PropertyDefinition typeSpecificProperty, Map allDataTypes) { - propertyOperation.validateAndUpdatePropertyValue(typeSpecificProperty.getType(), - property.getValue(), typeSpecificProperty.getSchemaType(), allDataTypes) - .left() - .on( error -> - exceptionUtils.rollBackAndThrow( - ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()) - ); + propertyOperation + .validateAndUpdatePropertyValue(typeSpecificProperty.getType(), property.getValue(), typeSpecificProperty.getSchemaType(), allDataTypes) + .left().on(error -> exceptionUtils.rollBackAndThrow(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName())); } - private PropertyDefinition isPropertyInsideAnnotationTypeProperties( - List dbAnnotationTypeDefinitionProperties, PropertyDefinition property) { + private PropertyDefinition isPropertyInsideAnnotationTypeProperties(List dbAnnotationTypeDefinitionProperties, + PropertyDefinition property) { Optional optionalResult = dbAnnotationTypeDefinitionProperties.stream() - .filter(prop -> prop.getName() - .equals(property.getName())) - .findFirst(); - if (optionalResult.isPresent()){ + .filter(prop -> prop.getName().equals(property.getName())).findFirst(); + if (optionalResult.isPresent()) { return optionalResult.get(); } - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - ActionStatus.PROPERTY_NOT_FOUND, property.getType(), property.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, property.getType(), property.getName()); exceptionUtils.rollBackAndThrow(responseFormat); return null; } - public Either iterateOverProperties(List properties){ + public Either iterateOverProperties(List properties) { Either eitherResult = Either.left(true); String type = null; String innerType = null; for (PropertyDefinition property : properties) { if (!propertyOperation.isPropertyTypeValid(property)) { log.info("Invalid type for property {}", property); - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); eitherResult = Either.right(responseFormat); break; } - Either, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); if (allDataTypes.isRight()) { JanusGraphOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to validate property. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); + BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to validate property. Status is " + status, + BeEcompErrorManager.ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); } - type = property.getType(); - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { ResponseFormat responseFormat = validateMapOrListPropertyType(property, allDataTypes.left().value()); - if(responseFormat != null) - break; + if (responseFormat != null) { + break; + } } - if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) { log.info("Invalid default value for property {}", 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()); + 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()); + responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); } eitherResult = Either.right(responseFormat); break; - } } return eitherResult; @@ -147,15 +135,12 @@ public class PropertyValidator { private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, Map allDataTypes) { ResponseFormat responseFormat = null; - ImmutablePair propertyInnerTypeValid = propertyOperation - .isPropertyInnerTypeValid(property, allDataTypes); + ImmutablePair propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes); String propertyInnerType = propertyInnerTypeValid.getLeft(); if (!propertyInnerTypeValid.getRight().booleanValue()) { log.info("Invalid inner type for property {}", property); - responseFormat = componentsUtils.getResponseFormat( - ActionStatus.INVALID_PROPERTY_INNER_TYPE, propertyInnerType, property.getName()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, propertyInnerType, property.getName()); } return responseFormat; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/RequirementValidation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/RequirementValidation.java index 030684ebb5..7dd38bb2c1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/RequirementValidation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/RequirementValidation.java @@ -13,10 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.components.validation; import fj.data.Either; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -28,13 +33,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - @Component("requirementValidation") public class RequirementValidation { @@ -42,13 +40,10 @@ public class RequirementValidation { private static final String REQUIREMENT_NOT_FOUND_IN_COMPONENT = "Requirement not found in component {} "; private static final Pattern NAME_VALIDATION_REGEX_PATTERN = Pattern.compile("^[a-zA-Z0-9_.]*$"); - public Either validateRequirements( - Collection requirements, - org.openecomp.sdc.be.model.Component component, boolean isUpdate) { - - for(RequirementDefinition requirementDefinition : requirements) { - Either requirementValidationResponse - = validateRequirement(requirementDefinition, component, isUpdate); + public Either validateRequirements(Collection requirements, + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { + for (RequirementDefinition requirementDefinition : requirements) { + Either requirementValidationResponse = validateRequirement(requirementDefinition, component, isUpdate); if (requirementValidationResponse.isRight()) { return requirementValidationResponse; } @@ -56,34 +51,27 @@ public class RequirementValidation { return Either.left(Boolean.TRUE); } - private Either validateRequirement( - RequirementDefinition requirementDefinition, - org.openecomp.sdc.be.model.Component component, - boolean isUpdate) { + private Either validateRequirement(RequirementDefinition requirementDefinition, + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { ResponseFormatManager responseFormatManager = getResponseFormatManager(); - if(isUpdate) { - Either requirementExistValidationEither - = isRequirementExist(requirementDefinition, responseFormatManager, component); + if (isUpdate) { + Either requirementExistValidationEither = isRequirementExist(requirementDefinition, responseFormatManager, + component); if (requirementExistValidationEither.isRight()) { return Either.right(requirementExistValidationEither.right().value()); } } - - Either requirementNameValidationResponse - = isRequirementNameValid(requirementDefinition, responseFormatManager, - component, isUpdate); + Either requirementNameValidationResponse = isRequirementNameValid(requirementDefinition, responseFormatManager, + component, isUpdate); if (requirementNameValidationResponse.isRight()) { return Either.right(requirementNameValidationResponse.right().value()); } - - Either requirementTypeEmptyEither = - isRequirementCapabilityEmpty(responseFormatManager, - requirementDefinition.getCapability()); + Either requirementTypeEmptyEither = isRequirementCapabilityEmpty(responseFormatManager, + requirementDefinition.getCapability()); if (requirementTypeEmptyEither.isRight()) { return Either.right(requirementTypeEmptyEither.right().value()); } - Either requirementOccurrencesValidationEither = - validateOccurrences(requirementDefinition, responseFormatManager); + Either requirementOccurrencesValidationEither = validateOccurrences(requirementDefinition, responseFormatManager); if (requirementOccurrencesValidationEither.isRight()) { return Either.right(requirementOccurrencesValidationEither.right().value()); } @@ -94,10 +82,9 @@ public class RequirementValidation { ResponseFormatManager responseFormatManager) { String maxOccurrences = requirementDefinition.getMaxOccurrences(); String minOccurrences = requirementDefinition.getMinOccurrences(); - if(maxOccurrences != null && minOccurrences !=null) { - Either requirementOccurrencesValidationEither = - validateOccurrences(responseFormatManager, minOccurrences, - maxOccurrences); + if (maxOccurrences != null && minOccurrences != null) { + Either requirementOccurrencesValidationEither = validateOccurrences(responseFormatManager, minOccurrences, + maxOccurrences); if (requirementOccurrencesValidationEither.isRight()) { return Either.right(requirementOccurrencesValidationEither.right().value()); } @@ -105,55 +92,44 @@ public class RequirementValidation { return Either.left(Boolean.TRUE); } - private Either isRequirementNameValid( - RequirementDefinition requirementDefinition, - ResponseFormatManager responseFormatManager, - org.openecomp.sdc.be.model.Component component, boolean isUpdate) { - Either requirementNameEmptyEither = - isRequirementNameEmpty(responseFormatManager, requirementDefinition.getName()); + private Either isRequirementNameValid(RequirementDefinition requirementDefinition, + ResponseFormatManager responseFormatManager, + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { + Either requirementNameEmptyEither = isRequirementNameEmpty(responseFormatManager, requirementDefinition.getName()); if (requirementNameEmptyEither.isRight()) { return Either.right(requirementNameEmptyEither.right().value()); } - - Either requirementNameRegexValidationResponse = - isRequirementNameRegexValid(responseFormatManager, requirementDefinition.getName()); + Either requirementNameRegexValidationResponse = isRequirementNameRegexValid(responseFormatManager, + requirementDefinition.getName()); if (requirementNameRegexValidationResponse.isRight()) { return Either.right(requirementNameRegexValidationResponse.right().value()); } - - Either requirementNameUniqueResponse - = validateRequirementNameUnique(requirementDefinition, - component, isUpdate ); - if(requirementNameUniqueResponse.isRight()) { + Either requirementNameUniqueResponse = validateRequirementNameUnique(requirementDefinition, component, isUpdate); + if (requirementNameUniqueResponse.isRight()) { return Either.right(requirementNameUniqueResponse.right().value()); } if (!requirementNameUniqueResponse.left().value()) { LOGGER.error("Requirement name {} already in use ", requirementDefinition.getName()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .REQUIREMENT_NAME_ALREADY_IN_USE, requirementDefinition.getName()); + ResponseFormat errorResponse = responseFormatManager + .getResponseFormat(ActionStatus.REQUIREMENT_NAME_ALREADY_IN_USE, requirementDefinition.getName()); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either isRequirementNameEmpty( - ResponseFormatManager responseFormatManager, - String requirementName) { + private Either isRequirementNameEmpty(ResponseFormatManager responseFormatManager, String requirementName) { if (StringUtils.isEmpty(requirementName)) { LOGGER.error("Requirement Name is mandatory"); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .REQUIREMENT_NAME_MANDATORY); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_NAME_MANDATORY); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either validateOccurrences ( - ResponseFormatManager responseFormatManager, - String minOccurrences, String maxOccurrences ) { + private Either validateOccurrences(ResponseFormatManager responseFormatManager, String minOccurrences, + String maxOccurrences) { try { - if (StringUtils.isNotEmpty(maxOccurrences) && "UNBOUNDED".equalsIgnoreCase(maxOccurrences) - && Integer.parseInt(minOccurrences) >= 0) { + if (StringUtils.isNotEmpty(maxOccurrences) && "UNBOUNDED".equalsIgnoreCase(maxOccurrences) && Integer.parseInt(minOccurrences) >= 0) { return Either.left(Boolean.TRUE); } else if (Integer.parseInt(minOccurrences) < 0) { LOGGER.debug("Invalid occurrences format.low_bound occurrence negative {}", minOccurrences); @@ -161,8 +137,8 @@ public class RequirementValidation { return Either.right(responseFormat); } else if (Integer.parseInt(maxOccurrences) < Integer.parseInt(minOccurrences)) { LOGGER.error("Requirement maxOccurrences should be greater than minOccurrences"); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .MAX_OCCURRENCES_SHOULD_BE_GREATER_THAN_MIN_OCCURRENCES); + ResponseFormat errorResponse = responseFormatManager + .getResponseFormat(ActionStatus.MAX_OCCURRENCES_SHOULD_BE_GREATER_THAN_MIN_OCCURRENCES); return Either.right(errorResponse); } } catch (NumberFormatException ex) { @@ -172,94 +148,72 @@ public class RequirementValidation { } return Either.left(Boolean.TRUE); } - private Either isRequirementCapabilityEmpty( - ResponseFormatManager responseFormatManager, - String requirementCapability) { + + private Either isRequirementCapabilityEmpty(ResponseFormatManager responseFormatManager, String requirementCapability) { if (StringUtils.isEmpty(requirementCapability)) { LOGGER.error("Requirement capability is mandatory"); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .REQUIREMENT_CAPABILITY_MANDATORY); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_CAPABILITY_MANDATORY); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either validateRequirementNameUnique( - RequirementDefinition requirementDefinition, - org.openecomp.sdc.be.model.Component component, - boolean isUpdate) { + private Either validateRequirementNameUnique(RequirementDefinition requirementDefinition, + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { boolean isRequirementNameUnique = false; - Map> componentRequirements = component.getRequirements(); - if(MapUtils.isEmpty(componentRequirements)){ + if (MapUtils.isEmpty(componentRequirements)) { return Either.left(true); } - List requirementDefinitionList = componentRequirements.values() - .stream().flatMap(Collection::stream).collect(Collectors.toList()); - - if(CollectionUtils.isEmpty(requirementDefinitionList)){ + List requirementDefinitionList = componentRequirements.values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(requirementDefinitionList)) { return Either.left(true); } - Map requirementNameMap = new HashMap<>(); - requirementDefinitionList.forEach(requirement -> requirementNameMap - .put(requirement.getUniqueId(), requirement.getName())); - - if (!requirementNameMap.values().contains(requirementDefinition.getName())){ + requirementDefinitionList.forEach(requirement -> requirementNameMap.put(requirement.getUniqueId(), requirement.getName())); + if (!requirementNameMap.values().contains(requirementDefinition.getName())) { isRequirementNameUnique = true; } - if (!isRequirementNameUnique && isUpdate){ - List> reqNamesEntry = requirementNameMap.entrySet() - .stream().filter(entry -> entry.getValue().equalsIgnoreCase(requirementDefinition.getName())) - .collect(Collectors.toList()); - if(reqNamesEntry.size() == 1 && reqNamesEntry.get(0).getKey() - .equals(requirementDefinition.getUniqueId())) { + if (!isRequirementNameUnique && isUpdate) { + List> reqNamesEntry = requirementNameMap.entrySet().stream() + .filter(entry -> entry.getValue().equalsIgnoreCase(requirementDefinition.getName())).collect(Collectors.toList()); + if (reqNamesEntry.size() == 1 && reqNamesEntry.get(0).getKey().equals(requirementDefinition.getUniqueId())) { isRequirementNameUnique = true; } } return Either.left(isRequirementNameUnique); } - private Either isRequirementExist( - RequirementDefinition definition, - ResponseFormatManager responseFormatManager, - org.openecomp.sdc.be.model.Component component) { + private Either isRequirementExist(RequirementDefinition definition, ResponseFormatManager responseFormatManager, + org.openecomp.sdc.be.model.Component component) { Map> componentRequirements = component.getRequirements(); - if(MapUtils.isEmpty(componentRequirements)){ + if (MapUtils.isEmpty(componentRequirements)) { LOGGER.error(REQUIREMENT_NOT_FOUND_IN_COMPONENT, component.getUniqueId()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .REQUIREMENT_NOT_FOUND, component.getUniqueId()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, component.getUniqueId()); return Either.right(errorResponse); } - - List requirementDefinitionList = componentRequirements.values() - .stream().flatMap(Collection::stream).collect(Collectors.toList()); - if(CollectionUtils.isEmpty(requirementDefinitionList)){ + List requirementDefinitionList = componentRequirements.values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(requirementDefinitionList)) { LOGGER.error(REQUIREMENT_NOT_FOUND_IN_COMPONENT, component.getUniqueId()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .REQUIREMENT_NOT_FOUND, component.getUniqueId()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, component.getUniqueId()); return Either.right(errorResponse); } boolean isRequirementExist = requirementDefinitionList.stream() - .anyMatch(requirementDefinition -> requirementDefinition.getUniqueId() - .equalsIgnoreCase(definition.getUniqueId())); - - if(!isRequirementExist) { + .anyMatch(requirementDefinition -> requirementDefinition.getUniqueId().equalsIgnoreCase(definition.getUniqueId())); + if (!isRequirementExist) { LOGGER.error(REQUIREMENT_NOT_FOUND_IN_COMPONENT, component.getUniqueId()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .REQUIREMENT_NOT_FOUND, component.getUniqueId()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, component.getUniqueId()); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either isRequirementNameRegexValid(ResponseFormatManager responseFormatManager, - String requirementName) { + private Either isRequirementNameRegexValid(ResponseFormatManager responseFormatManager, String requirementName) { if (!isValidRequirementName(requirementName)) { - LOGGER.error("Requirement name {} is invalid, Only alphanumeric chars, underscore and dot allowed", - requirementName); - ResponseFormat errorResponse = responseFormatManager - .getResponseFormat(ActionStatus.INVALID_REQUIREMENT_NAME, requirementName); + LOGGER.error("Requirement name {} is invalid, Only alphanumeric chars, underscore and dot allowed", requirementName); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.INVALID_REQUIREMENT_NAME, requirementName); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); @@ -272,6 +226,4 @@ public class RequirementValidation { protected ResponseFormatManager getResponseFormatManager() { return ResponseFormatManager.getInstance(); } - } - 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 index 695ee58300..b8ef79e21a 100644 --- 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 @@ -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. @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; import fj.data.Either; +import java.util.Arrays; +import java.util.List; +import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; @@ -38,15 +40,12 @@ import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -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 = Logger.getLogger(ServiceDistributionValidation.class); @Resource private ComponentsUtils componentsUtils; @@ -57,14 +56,16 @@ public class ServiceDistributionValidation { @Resource private IDistributionEngine distributionEngine; - public Either validateActivateServiceRequest(String serviceUUID, String opEnvId, User modifier, ServiceDistributionReqInfo data) { + 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()); + 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); @@ -77,7 +78,7 @@ public class ServiceDistributionValidation { Service abstractService = validateServiceExists(serviceUUID); validateDistributionServiceLifeCycleState(abstractService); } - + private Service validateServiceExists(String serviceUUID) { if (StringUtils.isEmpty(serviceUUID.trim())) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.BAD_REQUEST_MISSING_RESOURCE); @@ -86,10 +87,11 @@ public class ServiceDistributionValidation { 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()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue()); throw new ValidationException(responseFormat); } - return (Service)latestComponentByUuid.left().value(); + return (Service) latestComponentByUuid.left().value(); } private String validateWorkloadContext(ServiceDistributionReqInfo data) { @@ -112,15 +114,19 @@ public class ServiceDistributionValidation { 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()); + 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); + 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) { @@ -131,12 +137,12 @@ public class ServiceDistributionValidation { throw new ValidationException(responseFormat); } } + private void validateUserExists(String userId) { userValidations.validateUserExists(userId); } private void validateDistributionServiceLifeCycleState(Service serviceToActivate) { - validateServiceState(serviceToActivate, - Arrays.asList(LifecycleStateEnum.CERTIFIED)); + validateServiceState(serviceToActivate, Arrays.asList(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 index 29ed858031..cf4f84884f 100644 --- 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 @@ -40,51 +40,46 @@ import org.springframework.stereotype.Component; public class UserValidations { private static final Logger log = Logger.getLogger(UserValidations.class); - private final UserBusinessLogic userAdmin; + private final UserBusinessLogic userAdmin; public UserValidations(final UserBusinessLogic userAdmin) { - this.userAdmin = userAdmin; + this.userAdmin = userAdmin; } public void validateUserRole(final User user, final List roles) { - final Role userRole = Role.valueOf(user.getRole()); - if (roles != null && !roles.contains(userRole)) { - log.error(EcompLoggerErrorCode.PERMISSION_ERROR, this.getClass().getName(), - "user is not in appropriate role to perform action"); - throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); - } - } + final Role userRole = Role.valueOf(user.getRole()); + if (roles != null && !roles.contains(userRole)) { + log.error(EcompLoggerErrorCode.PERMISSION_ERROR, this.getClass().getName(), "user is not in appropriate role to perform action"); + throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION); + } + } - public ActionStatus validateUserExistsActionStatus(final String userId) { - if (!userAdmin.hasActiveUser(userId)) { - return ActionStatus.RESTRICTED_OPERATION; - } - return ActionStatus.OK; - } + public ActionStatus validateUserExistsActionStatus(final String userId) { + if (!userAdmin.hasActiveUser(userId)) { + return ActionStatus.RESTRICTED_OPERATION; + } + return ActionStatus.OK; + } - public User validateUserNotEmpty(final User user, - final String ecompErrorContext) { - final String userId = user.getUserId(); - if (StringUtils.isEmpty(userId)) { - log.error(EcompLoggerErrorCode.PERMISSION_ERROR, this.getClass().getName(), - "User header is missing "); - BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId()); + public User validateUserNotEmpty(final User user, final String ecompErrorContext) { + final String userId = user.getUserId(); + if (StringUtils.isEmpty(userId)) { + log.error(EcompLoggerErrorCode.PERMISSION_ERROR, this.getClass().getName(), "User header is missing "); + BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId()); throw new ByActionStatusComponentException(ActionStatus.MISSING_USER_ID); - } + } return user; - } - - public User validateUserExists(final String userId) { - final User user = userAdmin.getUser(userId); - if (UserStatusEnum.INACTIVE == user.getStatus()) { - throw new ByActionStatusComponentException(USER_INACTIVE, userId); - } - return user; - } - - public User validateUserExists(final User user) { - return validateUserExists(user.getUserId()); - } + } + public User validateUserExists(final String userId) { + final User user = userAdmin.getUser(userId); + if (UserStatusEnum.INACTIVE == user.getStatus()) { + throw new ByActionStatusComponentException(USER_INACTIVE, userId); + } + return user; + } + public User validateUserExists(final User user) { + return validateUserExists(user.getUserId()); + } } 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 index d65551a486..e2fed1ef63 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; import org.openecomp.sdc.exception.ResponseFormat; @@ -37,5 +36,4 @@ public class ValidationException extends RuntimeException { 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 index 085001f308..51603f6012 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation; import org.openecomp.sdc.common.log.wrappers.Logger; @@ -27,9 +26,8 @@ public class ValidationUtils { private static final Logger log = Logger.getLogger(ValidationUtils.class); - public static T throwValidationException(ResponseFormat responseFormat, String logMessage, Object ... logParams){ + public static T throwValidationException(ResponseFormat responseFormat, String logMessage, Object... logParams) { log.error(logMessage, logParams); throw new ValidationException(responseFormat); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentContactIdValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentContactIdValidator.java index 0c1face3ea..2a177c632e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentContactIdValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentContactIdValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.component; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; @@ -46,7 +45,6 @@ public class ComponentContactIdValidator implements ComponentFieldValidator { 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()); @@ -56,7 +54,8 @@ public class ComponentContactIdValidator implements ComponentFieldValidator { validateContactId(contactId, user, component, actionEnum, type); } - private void validateContactId(String contactId, User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type) { + private void validateContactId(String contactId, User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, + ComponentTypeEnum type) { if (contactId != null && !ValidationUtils.validateContactId(contactId)) { log.info("contact is invalid."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentDescriptionValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentDescriptionValidator.java index 47d9f8beee..8cf985feb6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentDescriptionValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentDescriptionValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.component; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; @@ -47,13 +46,12 @@ public class ComponentDescriptionValidator implements ComponentFieldValidator { ComponentTypeEnum type = component.getComponentType(); String description = component.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) { - auditErrorAndThrow(user,component, actionEnum, ActionStatus.COMPONENT_MISSING_DESCRIPTION); + auditErrorAndThrow(user, component, actionEnum, ActionStatus.COMPONENT_MISSING_DESCRIPTION); } - description = ValidationUtils.cleanUpText(description); - try{ + try { validateComponentDescription(description, type); - } catch(ComponentException e){ + } catch (ComponentException e) { ResponseFormat errorResponse = componentsUtils.getResponseFormat(e.getActionStatus(), component.getComponentType().getValue()); componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType()); throw e; @@ -61,7 +59,8 @@ public class ComponentDescriptionValidator implements ComponentFieldValidator { component.setDescription(description); } - private void auditErrorAndThrow(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, ActionStatus actionStatus) { + private void auditErrorAndThrow(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, + ActionStatus actionStatus) { ResponseFormat errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().getValue()); componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType()); throw new ByActionStatusComponentException(actionStatus, component.getComponentType().getValue()); @@ -70,9 +69,9 @@ public class ComponentDescriptionValidator implements ComponentFieldValidator { private void validateComponentDescription(String description, ComponentTypeEnum type) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), + "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); } - if (!ValidationUtils.validateCommentPattern(description)) { throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentFieldValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentFieldValidator.java index b8d6117f1b..c0bea45c3e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentFieldValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentFieldValidator.java @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.component; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; - public interface ComponentFieldValidator { void validateAndCorrectField(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentIconValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentIconValidator.java index 432ff41ebb..6bda4eac56 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentIconValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentIconValidator.java @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.component; +import java.util.Arrays; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; @@ -33,8 +33,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.Arrays; - @org.springframework.stereotype.Component public class ComponentIconValidator implements ComponentFieldValidator { @@ -59,12 +57,11 @@ public class ComponentIconValidator implements ComponentFieldValidator { if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) { validateAndSetDefaultIcon(icon, component); } else { - validateIcon(icon,component.getComponentType()); + validateIcon(icon, component.getComponentType()); } - - } catch(ComponentException e){ - ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() - : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); + } catch (ComponentException e) { + ResponseFormat responseFormat = + e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); throw e; } @@ -81,8 +78,7 @@ public class ComponentIconValidator implements ComponentFieldValidator { } } } catch (NullPointerException exp) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, - ComponentTypeEnum.SERVICE.getValue()); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); } componnet.setIcon(DEFAULT_ICON); } @@ -91,9 +87,9 @@ public class ComponentIconValidator implements ComponentFieldValidator { if (icon != null) { if (!ValidationUtils.validateIconLength(icon)) { log.debug("icon exceeds max length"); - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), + "" + ValidationUtils.ICON_MAX_LENGTH); } - if (!ValidationUtils.validateIcon(icon)) { log.info("icon is invalid."); throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_ICON, type.getValue()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentNameValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentNameValidator.java index 7b13d2ec5f..c9aa5fb42e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentNameValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentNameValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.component; import fj.data.Either; @@ -56,20 +55,18 @@ public class ComponentNameValidator implements ComponentFieldValidator { String componentName = component.getName(); if (StringUtils.isEmpty(componentName)) { log.debug("component name is empty"); - auditErrorAndThrow(user,component, actionEnum, ActionStatus.MISSING_COMPONENT_NAME); + auditErrorAndThrow(user, component, actionEnum, ActionStatus.MISSING_COMPONENT_NAME); } - if (!ValidationUtils.validateComponentNameLength(componentName)) { log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - auditErrorAndThrow(user,component, actionEnum, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT); + auditErrorAndThrow(user, component, actionEnum, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT); } - if (!ValidationUtils.validateComponentNamePattern(componentName)) { log.debug("Component name {} has invalid format", componentName); - auditErrorAndThrow(user,component, actionEnum, ActionStatus.INVALID_COMPONENT_NAME); + auditErrorAndThrow(user, component, actionEnum, ActionStatus.INVALID_COMPONENT_NAME); } if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) { - validateComponentNameUnique(user,component,actionEnum); + validateComponentNameUnique(user, component, actionEnum); } //TODO remove assignment here component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName)); @@ -80,15 +77,16 @@ public class ComponentNameValidator implements ComponentFieldValidator { log.debug("validate component name uniqueness for: {}", component.getName()); ComponentTypeEnum type = component.getComponentType(); ResourceTypeEnum resourceType = null; - if(component instanceof Resource){ - resourceType = ((Resource)component).getResourceType(); + if (component instanceof Resource) { + resourceType = ((Resource) component).getResourceType(); } - Either dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type); - + Either dataModelResponse = toscaOperationFacade + .validateComponentNameExists(component.getName(), resourceType, type); if (dataModelResponse.isLeft()) { if (dataModelResponse.left().value()) { log.info("Component with name {} already exists", component.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName()); componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); throw new ByResponseFormatComponentException(errorResponse); } @@ -101,7 +99,8 @@ public class ComponentNameValidator implements ComponentFieldValidator { throw new ByResponseFormatComponentException(errorResponse); } - private void auditErrorAndThrow(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, ActionStatus actionStatus) { + private void auditErrorAndThrow(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, + ActionStatus actionStatus) { ResponseFormat errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().getValue()); componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType()); throw new ByActionStatusComponentException(actionStatus, component.getComponentType().getValue()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentProjectCodeValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentProjectCodeValidator.java index 8d0fdf173b..29b4fdab75 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentProjectCodeValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentProjectCodeValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.component; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; @@ -34,7 +33,7 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; @org.springframework.stereotype.Component -public class ComponentProjectCodeValidator implements ComponentFieldValidator{ +public class ComponentProjectCodeValidator implements ComponentFieldValidator { private static final Logger log = Logger.getLogger(ComponentProjectCodeValidator.class.getName()); private ComponentsUtils componentsUtils; @@ -50,22 +49,18 @@ public class ComponentProjectCodeValidator implements ComponentFieldValidator{ } log.debug("validate ProjectCode name "); String projectCode = component.getProjectCode(); - if (!ValidationUtils.validateStringNotEmpty(projectCode)) { log.info("projectCode is empty is allowed CR."); return; } - try { validateProjectCode(projectCode); } catch (ComponentException exp) { ResponseFormat responseFormat = exp.getResponseFormat(); componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType(), - ResourceVersionInfo.newBuilder() - .build()); + ResourceVersionInfo.newBuilder().build()); throw exp; } - } private void validateProjectCode(String projectCode) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentTagsValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentTagsValidator.java index 243e0409b3..c1c785e7cb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentTagsValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentTagsValidator.java @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.component; +import java.util.ArrayList; +import java.util.List; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -32,9 +33,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.ArrayList; -import java.util.List; - @org.springframework.stereotype.Component public class ComponentTagsValidator implements ComponentFieldValidator { @@ -51,16 +49,17 @@ public class ComponentTagsValidator implements ComponentFieldValidator { List tagsList = component.getTags(); try { validateComponentTags(tagsList, component.getName(), component.getComponentType(), user, component, actionEnum); - } catch(ComponentException e){ - ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() - : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); + } catch (ComponentException e) { + ResponseFormat responseFormat = + e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType()); throw e; } ValidationUtils.removeDuplicateFromList(component.getTags()); } - protected void validateComponentTags(List tags, String name, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum action) { + protected void validateComponentTags(List tags, String name, ComponentTypeEnum componentType, User user, + org.openecomp.sdc.be.model.Component component, AuditingActionEnum action) { log.debug("validate component tags"); boolean includesComponentName = false; int tagListSize = 0; @@ -81,7 +80,6 @@ public class ComponentTagsValidator implements ComponentFieldValidator { if (tagListSize > 0) { tagListSize--; } - if (!includesComponentName) { log.debug("tags must include component name"); responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); @@ -90,7 +88,8 @@ public class ComponentTagsValidator implements ComponentFieldValidator { } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType); throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); } @@ -108,7 +107,8 @@ public class ComponentTagsValidator implements ComponentFieldValidator { return includesComponentName; } - private void validateTagLength(ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum action, String tag) { + private void validateTagLength(ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, + AuditingActionEnum action, String tag) { ResponseFormat responseFormat; if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentValidator.java index 3f300afe03..25072e926b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentValidator.java @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.component; +import java.util.List; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import java.util.List; - @Component public class ComponentValidator { @@ -41,8 +39,6 @@ public class ComponentValidator { } public void validate(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum) { - componentFieldValidators.stream().forEach(validator -> - validator.validateAndCorrectField(user,component,actionEnum)); + componentFieldValidators.stream().forEach(validator -> validator.validateAndCorrectField(user, component, actionEnum)); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceCategoryValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceCategoryValidator.java index 1fe14c3fda..f8b3fff6c2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceCategoryValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceCategoryValidator.java @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; +import static org.apache.commons.collections.CollectionUtils.isEmpty; + import fj.data.Either; +import java.util.List; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -35,16 +37,12 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.List; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; - @org.springframework.stereotype.Component public class ServiceCategoryValidator implements ServiceFieldValidator { private static final Logger log = Logger.getLogger(ServiceCategoryValidator.class.getName()); - private ComponentsUtils componentsUtils; protected IElementOperation elementDao; + private ComponentsUtils componentsUtils; public ServiceCategoryValidator(ComponentsUtils componentsUtils, IElementOperation elementDao) { this.componentsUtils = componentsUtils; @@ -55,7 +53,8 @@ public class ServiceCategoryValidator implements ServiceFieldValidator { public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) { log.debug("validate Service category"); if (isEmpty(service.getCategories())) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE); throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); } @@ -65,14 +64,14 @@ public class ServiceCategoryValidator implements ServiceFieldValidator { componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); throw new ByResponseFormatComponentException(responseFormat); } - } private 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()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue()); return Either.right(responseFormat); } CategoryDefinition category = list.get(0); @@ -83,10 +82,10 @@ public class ServiceCategoryValidator implements ServiceFieldValidator { } if (!ValidationUtils.validateStringNotEmpty(category.getName())) { log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + 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()) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceEnvironmentContextValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceEnvironmentContextValidator.java index 61206735ff..9a4468bb80 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceEnvironmentContextValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceEnvironmentContextValidator.java @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; +import java.util.List; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -27,10 +27,9 @@ import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import java.util.List; - @org.springframework.stereotype.Component public class ServiceEnvironmentContextValidator implements ServiceFieldValidator { + @Override public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) { String environmentContext = service.getEnvironmentContext(); @@ -38,15 +37,16 @@ public class ServiceEnvironmentContextValidator implements ServiceFieldValidator setDefaultEnvironmentContextFromConfiguration(service); return; } - List environmentContextValidValues = - ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext().getValidValues(); - if (!environmentContextValidValues.contains(environmentContext)) + List environmentContextValidValues = ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext() + .getValidValues(); + if (!environmentContextValidValues.contains(environmentContext)) { throw new ByActionStatusComponentException(ActionStatus.INVALID_ENVIRONMENT_CONTEXT, environmentContext); + } } private void setDefaultEnvironmentContextFromConfiguration(Service service) { - String defaultEnvironmentContext = - ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext().getDefaultValue(); + String defaultEnvironmentContext = ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext() + .getDefaultValue(); service.setEnvironmentContext(defaultEnvironmentContext); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFieldValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFieldValidator.java index 24d91c2325..4ff95a49a0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFieldValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFieldValidator.java @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; - public interface ServiceFieldValidator { + void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFunctionValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFunctionValidator.java index ff11629584..a9ea944093 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFunctionValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFunctionValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; import org.apache.commons.lang3.StringUtils; @@ -47,7 +46,7 @@ public class ServiceFunctionValidator implements ServiceFieldValidator { public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) { log.debug("validate service function"); String serviceFunction = service.getServiceFunction(); - if(serviceFunction == null) { + if (serviceFunction == null) { log.info("service function is null, assigned to empty value."); service.setServiceFunction(""); return; @@ -56,7 +55,7 @@ public class ServiceFunctionValidator implements ServiceFieldValidator { } private void validateServiceFunction(String serviceFunction) { - if (StringUtils.isEmpty(serviceFunction)){ + if (StringUtils.isEmpty(serviceFunction)) { return; } else { if (!ValidationUtils.validateServiceFunctionLength(serviceFunction)) { @@ -64,7 +63,6 @@ public class ServiceFunctionValidator implements ServiceFieldValidator { ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_EXCEEDS_LIMIT, "" + SERVICE_FUNCTION); throw new ByResponseFormatComponentException(errorResponse); } - if (!ValidationUtils.validateServiceMetadata(serviceFunction)) { log.info("service function is not valid."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERY, "" + SERVICE_FUNCTION); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceInstantiationTypeValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceInstantiationTypeValidator.java index baa59a17c7..7a34528bb0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceInstantiationTypeValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceInstantiationTypeValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; import org.apache.commons.lang3.StringUtils; @@ -34,6 +33,7 @@ import org.openecomp.sdc.exception.ResponseFormat; @org.springframework.stereotype.Component public class ServiceInstantiationTypeValidator implements ServiceFieldValidator { + private static final Logger log = Logger.getLogger(ServiceInstantiationTypeValidator.class.getName()); private ComponentsUtils componentsUtils; @@ -48,7 +48,7 @@ public class ServiceInstantiationTypeValidator implements ServiceFieldValidator if (StringUtils.isEmpty(instantiationType)) { service.setInstantiationType(InstantiationTypes.A_LA_CARTE.getValue()); } - if (!InstantiationTypes.containsName(service.getInstantiationType())){ + if (!InstantiationTypes.containsName(service.getInstantiationType())) { log.error("Recieved Instantiation type {} is not valid.", instantiationType); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_INSTANTIATION_TYPE, instantiationType); componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceNamingPolicyValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceNamingPolicyValidator.java index 5a7654226a..73acf20c53 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceNamingPolicyValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceNamingPolicyValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; import org.apache.commons.lang3.StringUtils; @@ -41,6 +40,7 @@ public class ServiceNamingPolicyValidator implements ServiceFieldValidator { public ServiceNamingPolicyValidator(ComponentsUtils componentsUtils) { this.componentsUtils = componentsUtils; } + @Override public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) { Boolean isEcompGeneratedCurr = service.isEcompGeneratedNaming(); @@ -50,7 +50,8 @@ public class ServiceNamingPolicyValidator implements ServiceFieldValidator { } if (isEcompGeneratedCurr) { if (!ValidationUtils.validateServiceNamingPolicyLength(namingPolicyUpdate)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NAMING_POLICY_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_NAMING_POLICY_MAX_SIZE); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NAMING_POLICY_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_NAMING_POLICY_MAX_SIZE); throw new ByResponseFormatComponentException(responseFormat); } if (StringUtils.isEmpty(namingPolicyUpdate)) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceRoleValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceRoleValidator.java index 59d2e837c5..10c831b909 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceRoleValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceRoleValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; import org.apache.commons.lang3.StringUtils; @@ -47,26 +46,23 @@ public class ServiceRoleValidator implements ServiceFieldValidator { public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) { log.debug("validate service role"); String serviceRole = service.getServiceRole(); - if (serviceRole != null){ - validateServiceRole(serviceRole); - } - + if (serviceRole != null) { + validateServiceRole(serviceRole); + } } private void validateServiceRole(String serviceRole) { - if (StringUtils.isEmpty(serviceRole)){ + if (StringUtils.isEmpty(serviceRole)) { return; } else { - if (!ValidationUtils.validateServiceRoleLength(serviceRole)) { log.info("service role exceeds limit."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_EXCEEDS_LIMIT, "" + SERVICE_ROLE); throw new ByResponseFormatComponentException(errorResponse); } - if (!ValidationUtils.validateServiceMetadata(serviceRole)) { log.info("service role is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERY, ""+ SERVICE_ROLE); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERY, "" + SERVICE_ROLE); throw new ByResponseFormatComponentException(errorResponse); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceTypeValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceTypeValidator.java index e5e2f0a9b9..2b592d8f9c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceTypeValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceTypeValidator.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; @@ -62,7 +61,7 @@ public class ServiceTypeValidator implements ServiceFieldValidator { } if (!ValidationUtils.validateServiceMetadata(serviceType)) { log.info("service type is not valid."); - throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERY,"" + SERVICE_TYPE); + throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERY, "" + SERVICE_TYPE); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceValidator.java index 5cf490dbf3..984e03d9a1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceValidator.java @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.components.validation.service; +import java.util.List; import org.openecomp.sdc.be.components.validation.component.ComponentFieldValidator; import org.openecomp.sdc.be.components.validation.component.ComponentValidator; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -28,14 +28,13 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.springframework.stereotype.Component; -import java.util.List; - @Component public class ServiceValidator extends ComponentValidator { private List serviceFieldValidators; - public ServiceValidator(ComponentsUtils componentsUtils, List componentFieldValidators, List serviceFieldValidators) { + public ServiceValidator(ComponentsUtils componentsUtils, List componentFieldValidators, + List serviceFieldValidators) { super(componentsUtils, componentFieldValidators); this.serviceFieldValidators = serviceFieldValidators; } @@ -43,7 +42,6 @@ public class ServiceValidator extends ComponentValidator { @Override public void validate(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum) { super.validate(user, component, actionEnum); - serviceFieldValidators.forEach(validator -> - validator.validateAndCorrectField(user,(Service)component,actionEnum)); + serviceFieldValidators.forEach(validator -> validator.validateAndCorrectField(user, (Service) component, actionEnum)); } } 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 index 156b73ce7b..bc1d9f4c22 100644 --- 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 @@ -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. @@ -17,22 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel; import java.util.Set; public class ForwardingPaths { - public ForwardingPaths() { - } + private Set forwardingPathToDelete; + + public ForwardingPaths() { + } - private Set forwardingPathToDelete; - public Set getForwardingPathToDelete() { - return forwardingPathToDelete; - } + public Set getForwardingPathToDelete() { + return forwardingPathToDelete; + } - public void setForwardingPathToDelete(Set forwardingPathToDelete) { - this.forwardingPathToDelete = 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 index 8985c60e37..6feab9eedf 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel; import java.util.HashMap; @@ -43,13 +42,16 @@ public class NameIdPair extends HashMap { if (!Objects.isNull(ownerId)) { setOwnerId(ownerId); } - } public NameIdPair(NameIdPair nameIdPair) { super(nameIdPair); } + public static final NameIdPair create(String name, String id) { + return new NameIdPair(name, id); + } + public String getName() { return get(NAME).toString(); } @@ -91,8 +93,12 @@ public class NameIdPair extends HashMap { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof NameIdPair)) return false; + if (this == o) { + return true; + } + if (!(o instanceof NameIdPair)) { + return false; + } NameIdPair that = (NameIdPair) o; return Objects.equals(getId(), that.getId()); } @@ -101,10 +107,4 @@ public class NameIdPair extends HashMap { 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 index e26c3f5ce2..81cc46a581 100644 --- 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 @@ -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. @@ -17,12 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel; import java.util.HashMap; public class NameIdPairWrapper extends HashMap { + public static final String ID = "id"; public static final String DATA = "data"; @@ -33,6 +33,7 @@ public class NameIdPairWrapper extends HashMap { super(); init(nameIdPair); } + public void init(NameIdPair nameIdPair) { setId(nameIdPair.getId()); setData(new NameIdPair(nameIdPair)); @@ -54,9 +55,7 @@ public class NameIdPairWrapper extends HashMap { put(DATA, data); } - public NameIdPair getNameIdPair(){ - return new NameIdPair(getData().getName(),getData().getId()); + 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 index cb1ddefe17..c55e1557c8 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel; import java.util.Set; 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 33aee95cd7..5b3f90c4c3 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 @@ -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. @@ -17,13 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel.api; public enum CategoryTypeEnum { - CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping"); - private String value; CategoryTypeEnum(String value) { @@ -33,5 +30,4 @@ public enum CategoryTypeEnum { 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 fc98400dd1..b134ed023f 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 @@ -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. @@ -17,11 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel.api; public enum HighestFilterEnum { - 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 9479c80246..01da5a2a98 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 @@ -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. @@ -17,9 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel.utils; +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.apache.commons.codec.binary.Base64; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -28,23 +33,16 @@ 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; - public class ArtifactUtils { - public static ArtifactDefinition findMasterArtifact(Map deplymentArtifact, List artifacts, List artifactsList) { + 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) { @@ -53,7 +51,8 @@ public class ArtifactUtils { ArtifactDefinition masterArtifact = null; for (ArtifactDefinition artifactInfo : artifacts) { String atrifactType = artifactInfo.getArtifactType(); - if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) { + if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType + .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) { masterArtifact = artifactInfo; continue; } @@ -66,61 +65,52 @@ public class ArtifactUtils { } public static Map buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, - ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, - byte[] artifactContentent, List updatedRequiredArtifacts, boolean isFromCsar) { - + ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, + String description, byte[] artifactContentent, + List updatedRequiredArtifacts, boolean isFromCsar) { Map json = new HashMap<>(); - if (artifactId != null && !artifactId.isEmpty()) + 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 = 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(ArtifactTemplateInfo::getFileName).collect(Collectors.toList())); + 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(ArtifactTemplateInfo::getFileName).collect(Collectors.toList())); return json; } - public static Map buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, - byte[] artifactContentent, int atrifactLabelCounter, boolean isFromcsar) { - + public static Map buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, + int atrifactLabelCounter, boolean isFromcsar) { 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"); - json.put(Constants.IS_FROM_CSAR, isFromcsar); - + json.put(Constants.IS_FROM_CSAR, isFromcsar); String encodedPayload = Base64.encodeBase64String(artifactContentent); - json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); String displayName = artifactName; - if (artifactName.lastIndexOf(".") > 0) + 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(ArtifactTemplateInfo::getFileName).collect(Collectors.toList())); + 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(ArtifactTemplateInfo::getFileName).collect(Collectors.toList())); return json; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ConstraintConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ConstraintConvertor.java index 7a6697e77e..877f8c4093 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ConstraintConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ConstraintConvertor.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel.utils; import com.google.common.collect.ImmutableMap; @@ -37,8 +36,6 @@ import org.yaml.snakeyaml.Yaml; public class ConstraintConvertor { - private static final Logger logger = LoggerFactory.getLogger(ConstraintConvertor.class); - public static final String EQUAL_OPERATOR = ConstraintType.EQUAL.getTypes().get(1); public static final String GREATER_THAN_OPERATOR = ConstraintType.GREATER_THAN.getTypes().get(1); public static final String LESS_THAN_OPERATOR = ConstraintType.LESS_THAN.getTypes().get(1); @@ -46,11 +43,10 @@ public class ConstraintConvertor { public static final String PROPERTY_CONSTRAINT = "property"; public static final String SERVICE_INPUT_CONSTRAINT = "service_input"; public static final String SELF = "SELF"; - private static Set SUPPORTED_CONSTRAINT_LIST = - ImmutableSet.of(EQUAL_OPERATOR, GREATER_THAN_OPERATOR, LESS_THAN_OPERATOR); - - private static Set SUPPORTED_FUNCTIONS = - ImmutableSet.of(ToscaFunctions.GET_INPUT.getFunctionName(), ToscaFunctions.GET_PROPERTY.getFunctionName()); + private static final Logger logger = LoggerFactory.getLogger(ConstraintConvertor.class); + private static Set SUPPORTED_CONSTRAINT_LIST = ImmutableSet.of(EQUAL_OPERATOR, GREATER_THAN_OPERATOR, LESS_THAN_OPERATOR); + private static Set SUPPORTED_FUNCTIONS = ImmutableSet + .of(ToscaFunctions.GET_INPUT.getFunctionName(), ToscaFunctions.GET_PROPERTY.getFunctionName()); public UIConstraint convert(String inConstraint) { Yaml yamlSource = new Yaml(); @@ -109,7 +105,7 @@ public class ConstraintConvertor { uiConstraint.setValue(value.get(1)); return uiConstraint; } - return null; + return null; } public List convertToList(List uiConstraints) { @@ -127,7 +123,6 @@ public class ConstraintConvertor { try { Map map1 = new HashMap(); Map map2 = new HashMap(); - map1.put(uiConstraint.getServicePropertyName(), map2); if (uiConstraint.getSourceType().equals(STATIC_CONSTRAINT)) { Object value = uiConstraint.getValue(); @@ -143,7 +138,6 @@ public class ConstraintConvertor { Map map3 = ImmutableMap.of(ToscaFunctions.GET_INPUT.getFunctionName(), uiConstraint.getValue()); map2.put(uiConstraint.getConstraintOperator(), map3); } - Yaml yamlSource = new Yaml(); return yamlSource.dump(map1); } catch (NullPointerException ex) { @@ -186,6 +180,5 @@ public class ConstraintConvertor { return handleMap(uiConstraint, constraintValue); } 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 cd6351cf9e..d1220b9441 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel.utils; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; @@ -25,52 +24,51 @@ 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; - - default: - // doesn't support subcategories or grouping + case SERVICE: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ServiceNewCategory; + break; + default: + // doesn't support subcategories or grouping + break; + } break; - } - break; - case RESOURCE: - switch (categoryType) { - case CATEGORY: - res = NodeTypeEnum.ResourceNewCategory; + case RESOURCE: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ResourceNewCategory; + break; + case SUBCATEGORY: + res = NodeTypeEnum.ResourceSubcategory; + break; + default: + // doesn't support grouping + break; + } break; - case SUBCATEGORY: - res = NodeTypeEnum.ResourceSubcategory; + case PRODUCT: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ProductCategory; + break; + case SUBCATEGORY: + res = NodeTypeEnum.ProductSubcategory; + break; + case GROUPING: + res = NodeTypeEnum.ProductGrouping; + break; + } 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/PropertyValueConstraintValidationUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtil.java index 24d4b2f1b8..9569247047 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtil.java @@ -13,12 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.datamodel.utils; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import fj.data.Either; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.collections4.MapUtils; @@ -40,47 +46,34 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - public class PropertyValueConstraintValidationUtil { private static final String UNDERSCORE = "_"; - private static final String VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY = - "%nValue provided in invalid format for %s property"; - private Map dataTypeDefinitionCache; + private static final String VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY = "%nValue provided in invalid format for %s property"; private static final Logger logger = LoggerFactory.getLogger(PropertyValueConstraintValidationUtil.class); + private static final String IGNORE_PROPERTY_VALUE_START_WITH = "{\"get_input\":"; + private Map dataTypeDefinitionCache; private ObjectMapper objectMapper = new ObjectMapper(); private List errorMessages = new ArrayList<>(); private StringBuilder completePropertyName; private String completeInputName; - private static final String IGNORE_PROPERTY_VALUE_START_WITH = "{\"get_input\":"; public static PropertyValueConstraintValidationUtil getInstance() { return new PropertyValueConstraintValidationUtil(); } - public Either validatePropertyConstraints( - Collection propertyDefinitionList, - ApplicationDataTypeCache applicationDataTypeCache) { + public Either validatePropertyConstraints(Collection propertyDefinitionList, + ApplicationDataTypeCache applicationDataTypeCache) { ResponseFormatManager responseFormatManager = getResponseFormatManager(); dataTypeDefinitionCache = applicationDataTypeCache.getAll().left().value(); - CollectionUtils.emptyIfNull(propertyDefinitionList).stream() - .filter(this::isValuePresent) - .forEach(this::evaluatePropertyTypeForConstraintValidation); - + CollectionUtils.emptyIfNull(propertyDefinitionList).stream().filter(this::isValuePresent) + .forEach(this::evaluatePropertyTypeForConstraintValidation); if (CollectionUtils.isNotEmpty(errorMessages)) { logger.error("Properties with Invalid Data:", errorMessages); - ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus - .INVALID_PROPERTY_VALUES, String.join(",", errorMessages)); + ResponseFormat inputResponse = responseFormatManager + .getResponseFormat(ActionStatus.INVALID_PROPERTY_VALUES, String.join(",", errorMessages)); return Either.right(inputResponse); } - return Either.left(Boolean.TRUE); } @@ -88,69 +81,60 @@ public class PropertyValueConstraintValidationUtil { if (propertyDefinition instanceof InputDefinition) { return StringUtils.isNotEmpty(propertyDefinition.getDefaultValue()); } - return StringUtils.isNotEmpty(propertyDefinition.getValue()); } private void evaluatePropertyTypeForConstraintValidation(PropertyDefinition propertyDefinition) { - if (Objects.nonNull(propertyDefinition.getType()) - && dataTypeDefinitionCache.containsKey(propertyDefinition.getType())) { - + if (Objects.nonNull(propertyDefinition.getType()) && dataTypeDefinitionCache.containsKey(propertyDefinition.getType())) { completeInputName = ""; completePropertyName = new StringBuilder(); if (propertyDefinition instanceof InputDefinition) { completeInputName = propertyDefinition.getName(); propertyDefinition = getPropertyDefinitionObjectFromInputs(propertyDefinition); } - if (Objects.nonNull(propertyDefinition)) { - if (ToscaType.isPrimitiveType(propertyDefinition.getType())) { - propertyDefinition.setConstraints( - org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(), - dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints())); - evaluateConstraintsOnProperty(propertyDefinition); - } else if (ToscaType.isCollectionType(propertyDefinition.getType())) { - propertyDefinition.setConstraints( - org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(), - dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints())); - evaluateConstraintsOnProperty(propertyDefinition); - evaluateCollectionTypeProperties(propertyDefinition); - } else { - setCompletePropertyName(propertyDefinition); - evaluateComplexTypeProperties(propertyDefinition); - } - } + if (ToscaType.isPrimitiveType(propertyDefinition.getType())) { + propertyDefinition.setConstraints(org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(), + dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints())); + evaluateConstraintsOnProperty(propertyDefinition); + } else if (ToscaType.isCollectionType(propertyDefinition.getType())) { + propertyDefinition.setConstraints(org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(), + dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints())); + evaluateConstraintsOnProperty(propertyDefinition); + evaluateCollectionTypeProperties(propertyDefinition); + } else { + setCompletePropertyName(propertyDefinition); + evaluateComplexTypeProperties(propertyDefinition); + } + } } else { errorMessages.add("\nUnsupported datatype found for property " + getCompletePropertyName(propertyDefinition)); } } private void setCompletePropertyName(PropertyDefinition propertyDefinition) { - if(StringUtils.isNotBlank(propertyDefinition.getUniqueId())) { - completePropertyName.append( - propertyDefinition.getUniqueId().substring(propertyDefinition.getUniqueId().lastIndexOf('.') + 1)); + if (StringUtils.isNotBlank(propertyDefinition.getUniqueId())) { + completePropertyName.append(propertyDefinition.getUniqueId().substring(propertyDefinition.getUniqueId().lastIndexOf('.') + 1)); } } private void evaluateConstraintsOnProperty(PropertyDefinition propertyDefinition) { ToscaType toscaType = ToscaType.isValidType(propertyDefinition.getType()); - if (isPropertyNotMappedAsInput(propertyDefinition) - && CollectionUtils.isNotEmpty(propertyDefinition.getConstraints()) - && isValidValueConstraintPresent(propertyDefinition.getConstraints())) { + if (isPropertyNotMappedAsInput(propertyDefinition) && CollectionUtils.isNotEmpty(propertyDefinition.getConstraints()) + && isValidValueConstraintPresent(propertyDefinition.getConstraints())) { for (PropertyConstraint propertyConstraint : propertyDefinition.getConstraints()) { try { propertyConstraint.initialize(toscaType); propertyConstraint.validate(toscaType, propertyDefinition.getValue()); } catch (ConstraintValueDoNotMatchPropertyTypeException | ConstraintViolationException exception) { - errorMessages.add("\n" + propertyConstraint.getErrorMessage( - toscaType, exception, getCompletePropertyName(propertyDefinition))); + errorMessages.add("\n" + propertyConstraint.getErrorMessage(toscaType, exception, getCompletePropertyName(propertyDefinition))); } } - } else if (isPropertyNotMappedAsInput(propertyDefinition) - && ToscaType.isPrimitiveType(propertyDefinition.getType()) - && !toscaType.isValidValue(propertyDefinition.getValue())) { - errorMessages.add(String.format("\nUnsupported value provided for %s property supported value " - + "type is %s.", getCompletePropertyName(propertyDefinition), toscaType.getType())); + } else if (isPropertyNotMappedAsInput(propertyDefinition) && ToscaType.isPrimitiveType(propertyDefinition.getType()) && !toscaType + .isValidValue(propertyDefinition.getValue())) { + errorMessages.add(String + .format("\nUnsupported value provided for %s property supported value " + "type is %s.", getCompletePropertyName(propertyDefinition), + toscaType.getType())); } } @@ -158,66 +142,49 @@ public class PropertyValueConstraintValidationUtil { return !propertyDefinition.getValue().startsWith(IGNORE_PROPERTY_VALUE_START_WITH); } - private void checkAndEvaluatePrimitiveProperty(PropertyDefinition propertyDefinition, - DataTypeDefinition dataTypeDefinition) { - if (ToscaType.isPrimitiveType(dataTypeDefinition.getName()) - && CollectionUtils.isNotEmpty(dataTypeDefinition.getConstraints())) { - + private void checkAndEvaluatePrimitiveProperty(PropertyDefinition propertyDefinition, DataTypeDefinition dataTypeDefinition) { + if (ToscaType.isPrimitiveType(dataTypeDefinition.getName()) && CollectionUtils.isNotEmpty(dataTypeDefinition.getConstraints())) { PropertyDefinition definition = new PropertyDefinition(); definition.setValue(propertyDefinition.getValue()); definition.setType(dataTypeDefinition.getName()); definition.setConstraints(dataTypeDefinition.getConstraints()); - evaluateConstraintsOnProperty(propertyDefinition); } } private void evaluateComplexTypeProperties(PropertyDefinition propertyDefinition) { - List propertyDefinitions = - dataTypeDefinitionCache.get(propertyDefinition.getType()).getProperties(); - try { - Map valueMap = - MapUtils.emptyIfNull(ConstraintUtil.parseToCollection(propertyDefinition.getValue(), - new TypeReference>() {})); - - if (CollectionUtils.isEmpty(propertyDefinitions)) { - checkAndEvaluatePrimitiveProperty(propertyDefinition, - dataTypeDefinitionCache.get(propertyDefinition.getType())); - } else { - ListUtils.emptyIfNull(propertyDefinitions) - .forEach(prop -> evaluateRegularComplexType(propertyDefinition, prop, valueMap)); - } - } catch (ConstraintValueDoNotMatchPropertyTypeException e) { - logger.debug(e.getMessage(), e); - errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, - getCompletePropertyName(propertyDefinition))); - } + List propertyDefinitions = dataTypeDefinitionCache.get(propertyDefinition.getType()).getProperties(); + try { + Map valueMap = MapUtils + .emptyIfNull(ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference>() { + })); + if (CollectionUtils.isEmpty(propertyDefinitions)) { + checkAndEvaluatePrimitiveProperty(propertyDefinition, dataTypeDefinitionCache.get(propertyDefinition.getType())); + } else { + ListUtils.emptyIfNull(propertyDefinitions).forEach(prop -> evaluateRegularComplexType(propertyDefinition, prop, valueMap)); + } + } catch (ConstraintValueDoNotMatchPropertyTypeException e) { + logger.debug(e.getMessage(), e); + errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition))); + } } - private void evaluateRegularComplexType(PropertyDefinition propertyDefinition, - PropertyDefinition prop, - Map valueMap) { + private void evaluateRegularComplexType(PropertyDefinition propertyDefinition, PropertyDefinition prop, Map valueMap) { try { if (valueMap.containsKey(prop.getName())) { if (ToscaType.isPrimitiveType(prop.getType())) { - evaluateConstraintsOnProperty(createPropertyDefinition(prop, - String.valueOf(valueMap.get(prop.getName())))); + evaluateConstraintsOnProperty(createPropertyDefinition(prop, String.valueOf(valueMap.get(prop.getName())))); } else if (ToscaType.isCollectionType(prop.getType())) { - - evaluateCollectionTypeProperties(createPropertyDefinition(prop, - objectMapper.writeValueAsString(valueMap.get(prop.getName())))); + evaluateCollectionTypeProperties(createPropertyDefinition(prop, objectMapper.writeValueAsString(valueMap.get(prop.getName())))); } else { completePropertyName.append(UNDERSCORE); completePropertyName.append(prop.getName()); - evaluateComplexTypeProperties( - createPropertyDefinition(prop, objectMapper.writeValueAsString( - valueMap.get(prop.getName())))); + evaluateComplexTypeProperties(createPropertyDefinition(prop, objectMapper.writeValueAsString(valueMap.get(prop.getName())))); } } } catch (IOException e) { logger.error(e.getMessage(), e); - errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, - getCompletePropertyName(propertyDefinition))); + errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition))); } } @@ -233,45 +200,37 @@ public class PropertyValueConstraintValidationUtil { private void evaluateListType(PropertyDefinition propertyDefinition) { try { String schemaType = propertyDefinition.getSchemaType(); - List list = ConstraintUtil.parseToCollection(propertyDefinition.getValue(), - new TypeReference>() {}); + List list = ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference>() { + }); evaluateCollectionType(propertyDefinition, list, schemaType); } catch (ConstraintValueDoNotMatchPropertyTypeException e) { logger.debug(e.getMessage(), e); - errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, - getCompletePropertyName(propertyDefinition))); + errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition))); } } private void evaluateMapType(PropertyDefinition propertyDefinition) { try { String schemaType = propertyDefinition.getSchemaType(); - Map map = ConstraintUtil.parseToCollection(propertyDefinition.getValue(), - new TypeReference>() { + Map map = ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference>() { }); evaluateCollectionType(propertyDefinition, map.values(), schemaType); } catch (ConstraintValueDoNotMatchPropertyTypeException e) { logger.debug(e.getMessage(), e); - errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, - getCompletePropertyName(propertyDefinition))); + errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition))); } } - private void evaluateCollectionPrimitiveSchemaType(PropertyDefinition propertyDefinition, - Object value, - String schemaType) { - if (Objects.nonNull(propertyDefinition.getSchema()) - && propertyDefinition.getSchema().getProperty() instanceof PropertyDefinition) { - propertyDefinition.setConstraints(((PropertyDefinition) propertyDefinition.getSchema() - .getProperty()).getConstraints()); + private void evaluateCollectionPrimitiveSchemaType(PropertyDefinition propertyDefinition, Object value, String schemaType) { + if (Objects.nonNull(propertyDefinition.getSchema()) && propertyDefinition.getSchema().getProperty() instanceof PropertyDefinition) { + propertyDefinition.setConstraints(((PropertyDefinition) propertyDefinition.getSchema().getProperty()).getConstraints()); propertyDefinition.setValue(String.valueOf(value)); propertyDefinition.setType(schemaType); evaluateConstraintsOnProperty(propertyDefinition); } } - private void evaluateCollectionType(PropertyDefinition propertyDefinition, - Collection valueList, - String schemaType) { + + private void evaluateCollectionType(PropertyDefinition propertyDefinition, Collection valueList, String schemaType) { for (Object value : valueList) { try { if (ToscaType.isPrimitiveType(schemaType)) { @@ -289,16 +248,15 @@ public class PropertyValueConstraintValidationUtil { } } catch (IOException e) { logger.debug(e.getMessage(), e); - errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, - getCompletePropertyName(propertyDefinition))); + errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition))); } } } private String getCompletePropertyName(PropertyDefinition propertyDefinition) { - return StringUtils.isNotBlank(completeInputName) ? completeInputName : - StringUtils.isBlank(completePropertyName) ? - propertyDefinition.getName() : completePropertyName + UNDERSCORE + propertyDefinition.getName(); + return StringUtils.isNotBlank(completeInputName) ? completeInputName + : StringUtils.isBlank(completePropertyName) ? propertyDefinition.getName() + : completePropertyName + UNDERSCORE + propertyDefinition.getName(); } private PropertyDefinition createPropertyDefinition(PropertyDefinition prop, String value) { @@ -308,30 +266,24 @@ public class PropertyValueConstraintValidationUtil { propertyDefinition.setType(prop.getType()); propertyDefinition.setConstraints(prop.getConstraints()); propertyDefinition.setSchema(prop.getSchema()); - return propertyDefinition; } private boolean isValidValueConstraintPresent(List propertyConstraints) { - return propertyConstraints.stream() - .anyMatch(propertyConstraint -> propertyConstraint instanceof ValidValuesConstraint); + return propertyConstraints.stream().anyMatch(propertyConstraint -> propertyConstraint instanceof ValidValuesConstraint); } - private PropertyDefinition getPropertyDefinitionObjectFromInputs( - PropertyDefinition property) { + private PropertyDefinition getPropertyDefinitionObjectFromInputs(PropertyDefinition property) { InputDefinition inputDefinition = (InputDefinition) property; PropertyDefinition propertyDefinition = null; - - if (CollectionUtils.isEmpty(inputDefinition.getProperties()) - || ToscaType.isPrimitiveType(inputDefinition.getProperties().get(0).getType())) { - propertyDefinition = new PropertyDefinition(); + if (CollectionUtils.isEmpty(inputDefinition.getProperties()) || ToscaType.isPrimitiveType(inputDefinition.getProperties().get(0).getType())) { + propertyDefinition = new PropertyDefinition(); propertyDefinition.setType(inputDefinition.getType()); propertyDefinition.setValue(inputDefinition.getDefaultValue()); propertyDefinition.setName(inputDefinition.getName()); } else if (Objects.nonNull(inputDefinition.getInputPath())) { propertyDefinition = evaluateComplexTypeInputs(inputDefinition); } - return propertyDefinition; } @@ -342,10 +294,9 @@ public class PropertyValueConstraintValidationUtil { if (inputPathArr.length > 1) { inputPathArr = ArrayUtils.remove(inputPathArr, 0); } - try { Map presentMap = inputMap; - for (int i = 0; i < inputPathArr.length ; i++) { + for (int i = 0; i < inputPathArr.length; i++) { if (i == inputPathArr.length - 1) { presentMap.computeIfAbsent(inputPathArr[i], k -> inputDefinition.getDefaultValue()); } else { @@ -353,7 +304,6 @@ public class PropertyValueConstraintValidationUtil { presentMap = (Map) presentMap.get(inputPathArr[i]); } } - if (CollectionUtils.isNotEmpty(inputDefinition.getProperties())) { propertyDefinition.setType(inputDefinition.getProperties().get(0).getType()); } @@ -361,10 +311,8 @@ public class PropertyValueConstraintValidationUtil { propertyDefinition.setValue(objectMapper.writeValueAsString(inputMap)); } catch (IOException e) { logger.error(e.getMessage(), e); - errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, - inputDefinition.getName())); + errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, inputDefinition.getName())); } - return propertyDefinition; } 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 e4a1187072..5bbf84906f 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.datamodel.utils; import static java.util.stream.Collectors.groupingBy; @@ -63,19 +62,35 @@ import org.openecomp.sdc.common.log.wrappers.Logger; @org.springframework.stereotype.Component("uiComponentDataConverter") public class UiComponentDataConverter { - private static final Logger log = Logger.getLogger(UiComponentDataConverter.class); public static final String INVALID_INPUT_GIVEN_TO_DATA_CONVERTER = "Invalid input given to data converter: {}"; + private static final Logger log = Logger.getLogger(UiComponentDataConverter.class); private final GroupTypeBusinessLogic groupTypeBusinessLogic; private final PolicyTypeBusinessLogic policyTypeBusinessLogic; - public UiComponentDataConverter(GroupTypeBusinessLogic groupTypeBusinessLogic, - PolicyTypeBusinessLogic policyTypeBusinessLogic) { + public UiComponentDataConverter(GroupTypeBusinessLogic groupTypeBusinessLogic, PolicyTypeBusinessLogic policyTypeBusinessLogic) { this.groupTypeBusinessLogic = groupTypeBusinessLogic; this.policyTypeBusinessLogic = policyTypeBusinessLogic; } - private void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, - String fieldName) { + 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; + } + + private void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) { ComponentFieldsEnum field = ComponentFieldsEnum.findByValue(fieldName); if (field == null) { log.error(INVALID_INPUT_GIVEN_TO_DATA_CONVERTER, fieldName); @@ -161,8 +176,7 @@ public class UiComponentDataConverter { } } - private void setSubstitutionFilter(final UiComponentDataTransfer dataTransfer, - final Component component) { + private void setSubstitutionFilter(final UiComponentDataTransfer dataTransfer, final Component component) { if (component.getSubstitutionFilterComponents() == null) { dataTransfer.setSubstitutionFilter(null); } else { @@ -172,34 +186,25 @@ public class UiComponentDataConverter { private void setPolicies(UiComponentDataTransfer dataTransfer, Component component) { Map policies = component.getPolicies(); - Set policyDefinitions = - MapUtils.isEmpty(policies) ? new HashSet<>() : new HashSet<>(policies.values()); - + Set policyDefinitions = MapUtils.isEmpty(policies) ? new HashSet<>() : new HashSet<>(policies.values()); policyDefinitions.addAll(getDeclaredPolicies(component.getComponentInstancesProperties())); - dataTransfer.setPolicies(new ArrayList<>(policyDefinitions)); } - private Set getDeclaredPolicies( - Map> componentInstanceProperties) { + private Set getDeclaredPolicies(Map> componentInstanceProperties) { if (MapUtils.isEmpty(componentInstanceProperties)) { return new HashSet<>(); } - Set declaredPolicies = new HashSet<>(); - for (Map.Entry> instancePropertyEntry : componentInstanceProperties - .entrySet()) { - declaredPolicies.addAll(instancePropertyEntry.getValue().stream() - .filter(property -> CollectionUtils.isNotEmpty(property.getGetPolicyValues())) - .map(instanceProperty -> PolicyUtils - .getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), instanceProperty)) - .collect(Collectors.toSet())); + for (Map.Entry> instancePropertyEntry : componentInstanceProperties.entrySet()) { + declaredPolicies.addAll( + instancePropertyEntry.getValue().stream().filter(property -> CollectionUtils.isNotEmpty(property.getGetPolicyValues())) + .map(instanceProperty -> PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), instanceProperty)) + .collect(Collectors.toSet())); } - return declaredPolicies; } - private void setComponentInstanceRelation(UiComponentDataTransfer dataTransfer, Component component) { if (component.getComponentInstancesRelations() == null) { dataTransfer.setComponentInstancesRelations(new ArrayList<>()); @@ -278,9 +283,7 @@ public class UiComponentDataConverter { private Map> getFilteredCapabilities(Component component) { if (component.getComponentType() != ComponentTypeEnum.SERVICE) { - return component.getCapabilities().values() - .stream() - .flatMap(Collection::stream) + return component.getCapabilities().values().stream().flatMap(Collection::stream) .filter(c -> c.getOwnerType() != CapabilityDataDefinition.OwnerType.GROUP) .collect(groupingBy(CapabilityDefinition::getType, toList())); } @@ -348,31 +351,23 @@ public class UiComponentDataConverter { if (groups == null) { dataTransfer.setGroups(new ArrayList<>()); } else { - Set nonExcludedGroupTypes = groupTypeBusinessLogic - .getExcludedGroupTypes(component.getActualComponentType()); - List nonExcludedGroups = groups.stream() - .filter(gd -> !nonExcludedGroupTypes.contains(gd.getType())) - .collect(toList()); + Set nonExcludedGroupTypes = groupTypeBusinessLogic.getExcludedGroupTypes(component.getActualComponentType()); + List nonExcludedGroups = groups.stream().filter(gd -> !nonExcludedGroupTypes.contains(gd.getType())).collect(toList()); dataTransfer.setGroups(nonExcludedGroups); } } private void setNonExcludedPolicies(UiComponentDataTransfer dataTransfer, Component component) { List policyDefinitions = component.resolvePoliciesList(); - Set nonExcludedPolicyTypes = policyTypeBusinessLogic - .getExcludedPolicyTypes(component.getActualComponentType()); - List nonExcludedPolicies = policyDefinitions.stream() - .filter(pd -> !nonExcludedPolicyTypes.contains(pd.getPolicyTypeName())) + Set nonExcludedPolicyTypes = policyTypeBusinessLogic.getExcludedPolicyTypes(component.getActualComponentType()); + List nonExcludedPolicies = policyDefinitions.stream().filter(pd -> !nonExcludedPolicyTypes.contains(pd.getPolicyTypeName())) .collect(toList()); dataTransfer.setPolicies(nonExcludedPolicies); } - public UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, - List paramsToReturn) { + public UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List paramsToReturn) { UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer(); - for (String fieldName : paramsToReturn) { - ComponentFieldsEnum field = ComponentFieldsEnum.findByValue(fieldName); if (field == null) { log.error(INVALID_INPUT_GIVEN_TO_DATA_CONVERTER, fieldName); @@ -386,10 +381,8 @@ public class UiComponentDataConverter { setAdditionalInfo(resource, dataTransfer); break; case METADATA: - UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), - resource.getDerivedFrom(), - (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition() - .getMetadataDataDefinition()); + UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), + (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); dataTransfer.setMetadata(metadata); break; case SUBSTITUTION_FILTER: @@ -398,27 +391,22 @@ public class UiComponentDataConverter { } else { final SubstitutionFilterConverter substitutionFilterConverter = new SubstitutionFilterConverter(); final Map filterUiMap = new HashMap<>(); - filterUiMap.put(resource.getUniqueId(), - substitutionFilterConverter.convertToUi(resource.getSubstitutionFilter())); + filterUiMap.put(resource.getUniqueId(), substitutionFilterConverter.convertToUi(resource.getSubstitutionFilter())); dataTransfer.setSubstitutionFilterForTopologyTemplate(filterUiMap); } break; - case NODE_FILTER: if (resource.getNodeFilterComponents() == null) { dataTransfer.setNodeFilterforNode(null); } else { final NodeFilterConverter nodeFilterConverter = new NodeFilterConverter(); - dataTransfer.setNodeFilterforNode( - nodeFilterConverter.convertDataMapToUI(resource.getNodeFilterComponents())); + dataTransfer.setNodeFilterforNode(nodeFilterConverter.convertDataMapToUI(resource.getNodeFilterComponents())); } break; - default: setUiTranferDataByFieldName(dataTransfer, resource, fieldName); } } - return dataTransfer; } @@ -455,8 +443,7 @@ public class UiComponentDataConverter { break; case METADATA: UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), - (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition() - .getMetadataDataDefinition()); + (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); dataTransfer.setMetadata(metadata); break; case NODE_FILTER: @@ -464,8 +451,7 @@ public class UiComponentDataConverter { dataTransfer.setNodeFilterforNode(null); } else { final NodeFilterConverter nodeFilterConverter = new NodeFilterConverter(); - dataTransfer.setNodeFilterforNode( - nodeFilterConverter.convertDataMapToUI(service.getNodeFilterComponents())); + dataTransfer.setNodeFilterforNode(nodeFilterConverter.convertDataMapToUI(service.getNodeFilterComponents())); } break; case SUBSTITUTION_FILTER: @@ -474,8 +460,7 @@ public class UiComponentDataConverter { } else { final SubstitutionFilterConverter substitutionFilterConverter = new SubstitutionFilterConverter(); final Map filterUiMap = new HashMap<>(); - filterUiMap.put(service.getUniqueId(), - substitutionFilterConverter.convertToUi(service.getSubstitutionFilter())); + filterUiMap.put(service.getUniqueId(), substitutionFilterConverter.convertToUi(service.getSubstitutionFilter())); dataTransfer.setSubstitutionFilterForTopologyTemplate(filterUiMap); } break; @@ -501,25 +486,4 @@ public class UiComponentDataConverter { dataTransfer.setForwardingPaths(service.getForwardingPaths()); } } - - 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 c8c2d94adc..87355df0d2 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.distribution; import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; @@ -28,6 +27,7 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData; public class AuditHandler { + private ComponentsUtils componentsUtils; private String instanceID; private RegistrationRequest registrationRequest; @@ -39,23 +39,30 @@ public class AuditHandler { this.registrationRequest = registrationRequest; } - - public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole , DistributionTopicData distributionTopicData) { - componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, + DistributionTopicData distributionTopicData) { + componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, + subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); } - public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, DistributionTopicData distributionTopicData) { - componentsUtils.auditDistributionEngine(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, + DistributionTopicData distributionTopicData) { + componentsUtils + .auditDistributionEngine(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, + 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())); - + 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())); + 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 81c41bc152..d293e9b615 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 @@ -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. @@ -17,12 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.distribution; +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; + import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fj.data.Either; +import java.util.List; +import javax.annotation.Resource; +import javax.ws.rs.core.Response; import org.apache.commons.collections.CollectionUtils; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; @@ -47,29 +53,31 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; -import javax.annotation.Resource; -import javax.ws.rs.core.Response; -import java.util.List; - -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 final Logger log = Logger.getLogger(DistributionBusinessLogic.class); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); @Resource private IDistributionEngine distributionEngine; - private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); @Resource private ICambriaHandler cambriaHandler; + 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); + } + private void initRequestEnvEndPointsAndKeys(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) { - if(CollectionUtils.isEmpty(registrationRequest.getDistEnvEndPoints())){ + if (CollectionUtils.isEmpty(registrationRequest.getDistEnvEndPoints())) { registrationRequest.setDistEnvEndPoints(config.getUebServers()); registrationRequest.setManagerApiPublicKey(config.getUebPublicKey()); registrationRequest.setManagerApiSecretKey(config.getUebSecretKey()); @@ -79,210 +87,148 @@ public class DistributionBusinessLogic { registrationRequest.setManagerApiSecretKey(environment.getUebSecretKey()); } } - public Either getUebServerList() { + public Either getUebServerList() { DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager() - .getDistributionEngineConfiguration(); - + .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); + ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); return Either.right(errorResponseWrapper); } - } - public void handleRegistration(Wrapper responseWrapper, RegistrationRequest registrationRequest, - AuditHandler auditHandler) { + public void handleRegistration(Wrapper responseWrapper, RegistrationRequest registrationRequest, AuditHandler auditHandler) { CambriaErrorResponse registerResponse = null; try { DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration(); - String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(), - registrationRequest.getDistrEnvName()); + String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); initRequestEnvEndPointsAndKeys(registrationRequest, config); - registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, - SubscriberTypeEnum.PRODUCER, statusTopicName); - + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName); auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER, - DistributionTopicData.newBuilder() - .statusTopic(statusTopicName) - .build()); + DistributionTopicData.newBuilder().statusTopic(statusTopicName).build()); 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); + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER, + statusTopicName); auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, - DistributionTopicData.newBuilder() - .statusTopic(statusTopicName) - .build()); + DistributionTopicData.newBuilder().statusTopic(statusTopicName).build()); registeredAsConsumerOnStatus = responseWrapper.isEmpty(); - } - if (responseWrapper.isEmpty()) { - String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), - registrationRequest.getDistrEnvName()); - registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, - SubscriberTypeEnum.CONSUMER, notificationTopicName); + String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER, + notificationTopicName); auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, - DistributionTopicData.newBuilder() - .notificationTopic(notificationTopicName) - .build()); + DistributionTopicData.newBuilder().notificationTopic(notificationTopicName).build()); } // Unregister Rollback if (!responseWrapper.isEmpty()) { if (isRegisteredAsProducerOnStatusSuccess) { - CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, - SubscriberTypeEnum.PRODUCER, statusTopicName); + CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER, + statusTopicName); auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER, - DistributionTopicData.newBuilder() - .statusTopic(statusTopicName) - .build()); + DistributionTopicData.newBuilder().statusTopic(statusTopicName).build()); } if (registeredAsConsumerOnStatus) { - CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, - SubscriberTypeEnum.CONSUMER, statusTopicName); + CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER, + statusTopicName); auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER, - DistributionTopicData.newBuilder() - .statusTopic(statusTopicName) - .build()); + DistributionTopicData.newBuilder().statusTopic(statusTopicName).build()); } } - if (responseWrapper.isEmpty()) { TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest); responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); } - } catch (Exception e) { log.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)); + 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) { + public void handleUnRegistration(Wrapper responseWrapper, RegistrationRequest unRegistrationRequest, AuditHandler auditHandler) { Wrapper cambriaResponseWrapper = new Wrapper<>(); try { String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName()); - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() - .getDistributionEngineConfiguration(); + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); initRequestEnvEndPointsAndKeys(unRegistrationRequest, config); - CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic( - unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName); + CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, + SubscriberTypeEnum.PRODUCER, statusTopicName); auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER, - DistributionTopicData.newBuilder() - .statusTopic(statusTopicName) - .build()); + DistributionTopicData.newBuilder().statusTopic(statusTopicName).build()); updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse); - String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName()); - CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic( - unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName); + CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, + SubscriberTypeEnum.CONSUMER, notificationTopicName); auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER, - DistributionTopicData.newBuilder() - .notificationTopic(notificationTopicName) - .build()); + DistributionTopicData.newBuilder().notificationTopic(notificationTopicName).build()); updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse); - // Success unregister both topics TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse( - getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), - getStatusTopicName(unRegistrationRequest.getDistrEnvName()), - unregisterClientConsumerTopicResponse.getOperationStatus(), - unregisterClientProducerTopicResponse.getOperationStatus()); - + 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()); + 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) { log.error("unregistered to topic failed", e); - Response errorResponse = buildErrorResponse( - getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); responseWrapper.setInnerElement(errorResponse); - } finally { auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement()); } } - private void updateResponseWrapper(Wrapper cambriaResponseWrapper, - CambriaErrorResponse currentResponse) { + 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) { - - log.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints()); + protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, SubscriberTypeEnum subscriberType, + String topicName) { + log.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, + unRegistrationRequest.getDistEnvEndPoints()); return cambriaHandler.unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), unRegistrationRequest.getManagerApiPublicKey(), - unRegistrationRequest.getManagerApiSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName); + unRegistrationRequest.getManagerApiSecretKey(), 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()); - + 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) { - + protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper responseWrapper, RegistrationRequest registrationRequest, + SubscriberTypeEnum subscriberType, String topicName) { String errorMsg; - // Register for notifications as consumer if (subscriberType == SubscriberTypeEnum.CONSUMER) { errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed"; @@ -291,24 +237,21 @@ public class DistributionBusinessLogic { else { errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed"; } - log.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints()); - CambriaErrorResponse registerToTopic = cambriaHandler.registerToTopic(registrationRequest.getDistEnvEndPoints(), - registrationRequest.getManagerApiPublicKey(), registrationRequest.getManagerApiSecretKey(), registrationRequest.getApiPublicKey(), - subscriberType, topicName); - + log.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, + registrationRequest.getDistEnvEndPoints()); + CambriaErrorResponse registerToTopic = cambriaHandler + .registerToTopic(registrationRequest.getDistEnvEndPoints(), registrationRequest.getManagerApiPublicKey(), + registrationRequest.getManagerApiSecretKey(), 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); + 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(); + return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); } public ResponseFormatManager getResponseFormatManager() { @@ -318,5 +261,4 @@ public class DistributionBusinessLogic { public IDistributionEngine getDistributionEngine() { return distributionEngine; } - } 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 3edb3d8f69..6fccd8ebff 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 @@ -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. @@ -17,9 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 1ce3621d84..4385d4dbd9 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.distribution.api.client; import java.util.List; @@ -27,6 +26,7 @@ import lombok.Setter; @Getter @Setter public class RegistrationRequest { + private String apiPublicKey; private String distrEnvName; private Boolean isConsumerToSdcDistrStatusTopic; @@ -39,7 +39,8 @@ public class RegistrationRequest { this.distrEnvName = distrEnvName; this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; } - public RegistrationRequest(String apiPublicKey, String distrEnvName, List distEnvEndPoints, boolean isConsumerToSdcDistrStatusTopic){ + + public RegistrationRequest(String apiPublicKey, String distrEnvName, List distEnvEndPoints, boolean isConsumerToSdcDistrStatusTopic) { this.apiPublicKey = apiPublicKey; this.distrEnvName = distrEnvName; 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 b0db19f541..60628901e9 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.distribution.api.client; import java.util.List; @@ -29,5 +28,6 @@ import lombok.Setter; @Setter @NoArgsConstructor(force = true) public class ServerListResponse { + private List 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 6b3e9e15e2..7612d1f0ef 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.distribution.api.client; import lombok.Getter; @@ -28,6 +27,7 @@ import lombok.Setter; @Setter @NoArgsConstructor(force = true) public class TopicRegistrationResponse { + String distrNotificationTopicName; String 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 55c3baef24..337b347b6d 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 @@ -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. @@ -17,19 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.distribution.api.client; import lombok.Getter; @Getter public class TopicUnregistrationResponse { + String distrNotificationTopicName; String distrStatusTopicName; CambriaOperationStatus notificationUnregisterResult; CambriaOperationStatus statusUnregisterResult; - public TopicUnregistrationResponse(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; 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 f0d329ec20..e0fb33534f 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 @@ -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. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.distribution.servlet; import com.jcabi.aspects.Loggable; @@ -33,6 +32,22 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import javax.inject.Inject; +import javax.inject.Singleton; +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 org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; @@ -48,30 +63,11 @@ import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import javax.inject.Inject; -import javax.inject.Singleton; -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 java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - /** * This Servlet serves external users to download artifacts. - * - * @author tgitelman * + * @author tgitelman */ - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Tags({@Tag(name = "SDC Distribution APIs")}) @@ -80,26 +76,22 @@ import java.util.Map; public class DistributionCatalogServlet extends BeGenericServlet { private static final String DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION = "download artifact failed with exception"; - private static final String MISSING_X_ECOMP_INSTANCE_ID_HEADER = "Missing X-ECOMP-InstanceID header"; - private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class); - private final ArtifactsBusinessLogic artifactsBusinessLogic; + private static final String MISSING_X_ECOMP_INSTANCE_ID_HEADER = "Missing X-ECOMP-InstanceID header"; + private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class); + private final ArtifactsBusinessLogic artifactsBusinessLogic; + @Context + private HttpServletRequest request; - @Inject - public DistributionCatalogServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - ArtifactsBusinessLogic artifactsBusinessLogic) { + @Inject + public DistributionCatalogServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + ArtifactsBusinessLogic artifactsBusinessLogic) { super(userBusinessLogic, componentsUtils); this.artifactsBusinessLogic = artifactsBusinessLogic; } - - @Context - private HttpServletRequest request; - // ******************************************************* // Download (GET) artifacts // **********************************************************/ /** - * * @param requestId * @param instanceIdHeader * @param accept @@ -113,51 +105,39 @@ public class DistributionCatalogServlet extends BeGenericServlet { @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Download service artifact", method = "GET", summary = "Returns downloaded artifact", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "400", - description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"), - @ApiResponse(responseCode = "404", - description = "Specified Service Version is not found - SVC4504"), - @ApiResponse(responseCode = "404", description = "Specified artifact is not found - SVC4505"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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")}) + @Operation(description = "Download service artifact", method = "GET", summary = "Returns downloaded artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"), + @ApiResponse(responseCode = "404", description = "Specified Service Version is not found - SVC4504"), + @ApiResponse(responseCode = "404", description = "Specified artifact is not found - SVC4505"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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")}) @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) public Response downloadServiceArtifact( - @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "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) { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "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) { String requestURI = request.getRequestURI(); Wrapper responseWrapper = validateInstanceIdHeader(new Wrapper<>(), instanceIdHeader, requestURI); - if(!responseWrapper.isEmpty()) { + if (!responseWrapper.isEmpty()) { return responseWrapper.getInnerElement(); } - try { byte[] downloadRsrcArtifactEither = artifactsBusinessLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); byte[] value = downloadRsrcArtifactEither; 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)); return buildOkResponse(responseFormat, is, headers); - } catch (ComponentException e) { getComponentsUtils().auditDistributionDownload(e.getResponseFormat(), new DistributionData(instanceIdHeader, requestURI)); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API"); @@ -177,7 +157,6 @@ public class DistributionCatalogServlet extends BeGenericServlet { } /** - * * @param requestId * @param instanceIdHeader * @param accept @@ -193,48 +172,36 @@ public class DistributionCatalogServlet extends BeGenericServlet { @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Download resource artifact", method = "GET", summary = "Returns downloaded artifact", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "400", - description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"), - @ApiResponse(responseCode = "404", - description = "Specified Resource Instance is not found - SVC4526"), - @ApiResponse(responseCode = "404", - description = "Specified Service Version is not found - SVC4504"), - @ApiResponse(responseCode = "404", description = "Specified artifact is not found - SVC4505"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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")}) + @Operation(description = "Download resource artifact", method = "GET", summary = "Returns downloaded artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"), + @ApiResponse(responseCode = "404", description = "Specified Resource Instance is not found - SVC4526"), + @ApiResponse(responseCode = "404", description = "Specified Service Version is not found - SVC4504"), + @ApiResponse(responseCode = "404", description = "Specified artifact is not found - SVC4505"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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")}) @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) public Response downloadResourceArtifact( - @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "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) { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "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) { String requestURI = request.getRequestURI(); Wrapper responseWrapper = validateInstanceIdHeader(new Wrapper<>(), instanceIdHeader, requestURI); - - if(!responseWrapper.isEmpty()) { + if (!responseWrapper.isEmpty()) { return responseWrapper.getInnerElement(); } - try { ArtifactsBusinessLogic artifactsLogic = getArtifactBL(request.getSession().getServletContext()); - byte[] downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName); + byte[] downloadRsrcArtifactEither = artifactsLogic + .downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName); byte[] value = downloadRsrcArtifactEither; // Returning 64-encoded as it was received during upload InputStream is = new ByteArrayInputStream(value); @@ -243,7 +210,6 @@ public class DistributionCatalogServlet extends BeGenericServlet { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); return buildOkResponse(responseFormat, is, headers); - } catch (ComponentException e) { getComponentsUtils().auditDistributionDownload(e.getResponseFormat(), new DistributionData(instanceIdHeader, requestURI)); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); @@ -253,7 +219,6 @@ public class DistributionCatalogServlet extends BeGenericServlet { } /** - * * @param requestId * @param instanceIdHeader * @param accept @@ -268,43 +233,34 @@ public class DistributionCatalogServlet extends BeGenericServlet { @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Download resource instance artifact", method = "GET", - summary = "Returns downloaded artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"), - @ApiResponse(responseCode = "404", description = "Specified Resource Instance is not found - SVC4526"), - @ApiResponse(responseCode = "404", description = "Specified Service Version is not found - SVC4504"), - @ApiResponse(responseCode = "404", description = "Specified artifact is not found - SVC4505"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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")}) + @Operation(description = "Download resource instance artifact", method = "GET", summary = "Returns downloaded artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"), + @ApiResponse(responseCode = "404", description = "Specified Resource Instance is not found - SVC4526"), + @ApiResponse(responseCode = "404", description = "Specified Service Version is not found - SVC4504"), + @ApiResponse(responseCode = "404", description = "Specified artifact is not found - SVC4505"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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")}) @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) public Response downloadResourceInstanceArtifactByName( - @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "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) { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "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) { String requestURI = request.getRequestURI(); Wrapper responseWrapper = validateInstanceIdHeader(new Wrapper<>(), instanceIdHeader, requestURI); - - if(!responseWrapper.isEmpty()) { + if (!responseWrapper.isEmpty()) { return responseWrapper.getInnerElement(); } - try { - byte[] downloadRsrcArtifactEither = artifactsBusinessLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName); + byte[] downloadRsrcArtifactEither = artifactsBusinessLogic + .downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName); byte[] value = downloadRsrcArtifactEither; // Returning 64-encoded as it was received during upload InputStream is = new ByteArrayInputStream(value); @@ -313,7 +269,6 @@ public class DistributionCatalogServlet extends BeGenericServlet { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); return buildOkResponse(responseFormat, is, headers); - } catch (ComponentException e) { getComponentsUtils().auditDistributionDownload(e.getResponseFormat(), new DistributionData(instanceIdHeader, requestURI)); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); 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 c6be01db5c..511e9971c7 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.distribution.servlet; import com.jcabi.aspects.Loggable; @@ -33,6 +32,17 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.inject.Inject; +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 org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -56,25 +66,11 @@ import org.openecomp.sdc.common.util.HttpUtil; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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; - /** * This Servlet serves external users for distribution purposes. * * @author tgitelman - * */ - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1") @Tags({@Tag(name = "SDC Distribution APIs")}) @@ -83,20 +79,18 @@ import javax.ws.rs.core.Response; public class DistributionServlet extends BeGenericServlet { private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; - private static final Logger log = Logger.getLogger(DistributionServlet.class); + private static final Logger log = Logger.getLogger(DistributionServlet.class); private final DistributionBusinessLogic distributionLogic; @Context private HttpServletRequest request; @Inject - public DistributionServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, DistributionBusinessLogic distributionLogic) { + public DistributionServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, DistributionBusinessLogic distributionLogic) { super(userBusinessLogic, componentsUtils); this.distributionLogic = distributionLogic; } /** - * * @param requestId * @param instanceId * @param accept @@ -107,46 +101,36 @@ public class DistributionServlet extends BeGenericServlet { @Path("/distributionUebCluster") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "UEB Server List", method = "GET", summary = "return the available UEB Server List", - responses = {@ApiResponse(responseCode = "200", - description = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", - content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ServerListResponse.class)))), - @ApiResponse(responseCode = "400", - description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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")}) + @Operation(description = "UEB Server List", method = "GET", summary = "return the available UEB Server List", responses = { + @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServerListResponse.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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")}) //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)})*/ @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) public Response getUebServerList( - @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) { 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().auditGetUebCluster(null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); return response; } - try { Either actionResponse = distributionLogic.getUebServerList(); - if (actionResponse.isRight()) { responseFormat = actionResponse.right().value(); response = buildErrorResponse(responseFormat); @@ -154,10 +138,8 @@ public class DistributionServlet extends BeGenericServlet { responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); response = buildOkResponse(responseFormat, actionResponse.left().value()); } - getComponentsUtils().auditGetUebCluster(instanceId, 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); @@ -165,11 +147,9 @@ public class DistributionServlet extends BeGenericServlet { getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); return buildErrorResponse(responseFormat); } - } /** - * * @param requestId * @param instanceId * @param accept @@ -183,92 +163,72 @@ public class DistributionServlet extends BeGenericServlet { @Path("/registerForDistribution") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(parameters = {@Parameter(name = "requestJson", required = true, - schema = @Schema(implementation = org.openecomp.sdc.be.distribution.api.client.RegistrationRequest.class))}, - description = "Subscription status", method = "POST", summary = "Subscribes for distribution notifications", - responses = {@ApiResponse(responseCode = "200", - description = "ECOMP component is successfully registered for distribution", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = TopicRegistrationResponse.class)))), - @ApiResponse(responseCode = "400", - description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "400", description = "Missing Body - POL4500"), - @ApiResponse(responseCode = "400", - description = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), - @ApiResponse(responseCode = "400", - description = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"), - @ApiResponse(responseCode = "400", - description = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + @Operation(parameters = { + @Parameter(name = "requestJson", required = true, schema = @Schema(implementation = org.openecomp.sdc.be.distribution.api.client.RegistrationRequest.class))}, description = "Subscription status", method = "POST", summary = "Subscribes for distribution notifications", responses = { + @ApiResponse(responseCode = "200", description = "ECOMP component is successfully registered for distribution", content = @Content(array = @ArraySchema(schema = @Schema(implementation = TopicRegistrationResponse.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "400", description = "Missing Body - POL4500"), + @ApiResponse(responseCode = "400", description = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), + @ApiResponse(responseCode = "400", description = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"), + @ApiResponse(responseCode = "400", description = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) public Response registerForDistribution( - @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, - @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter( hidden = true) String requestJson) { + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "Length of the request body", required = true) @HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(hidden = true) String requestJson) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - 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); } - if (responseWrapper.isEmpty()) { - distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement())); + distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), + buildAuditHandler(request, registrationRequestWrapper.getInnerElement())); } else { - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(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. + * 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. */ @GET @Path("/artifactTypes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Artifact types list", method = "GET", summary = "Fetches available artifact types list", - responses = {@ApiResponse(responseCode = "200", description = "Artifact types list fetched successfully", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "400", - description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + @Operation(description = "Artifact types list", method = "GET", summary = "Fetches available artifact types list", responses = { + @ApiResponse(responseCode = "200", description = "Artifact types list fetched successfully", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) public Response getValidArtifactTypes( - @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) { + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - Wrapper responseWrapper = new Wrapper<>(); - //TODO check if in use validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES); if (responseWrapper.isEmpty()) { @@ -294,46 +254,34 @@ public class DistributionServlet extends BeGenericServlet { @Path("/unRegisterForDistribution") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(parameters = @Parameter(name = "requestJson", required = true), description = "Subscription status", - method = "POST", summary = "Removes from subscription for distribution notifications", responses = { - @ApiResponse(responseCode = "204", description = "ECOMP component is successfully unregistered", - content = @Content(array = @ArraySchema( - schema = @Schema(implementation = TopicUnregistrationResponse.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "400", description = "Missing Body - POL4500"), - @ApiResponse(responseCode = "400", - description = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), - @ApiResponse(responseCode = "400", - description = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"), - @ApiResponse(responseCode = "400", - description = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + @Operation(parameters = @Parameter(name = "requestJson", required = true), description = "Subscription status", method = "POST", summary = "Removes from subscription for distribution notifications", responses = { + @ApiResponse(responseCode = "204", description = "ECOMP component is successfully unregistered", content = @Content(array = @ArraySchema(schema = @Schema(implementation = TopicUnregistrationResponse.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "400", description = "Missing Body - POL4500"), + @ApiResponse(responseCode = "400", description = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), + @ApiResponse(responseCode = "400", description = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"), + @ApiResponse(responseCode = "400", description = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) //TODO Edit the responses - @Parameters({@Parameter(name = "requestJson", required = true, schema = @Schema(implementation = org.openecomp.sdc.be.distribution.api.client.RegistrationRequest.class) , description = "json describe the artifact")}) + @Parameters({ + @Parameter(name = "requestJson", required = true, schema = @Schema(implementation = org.openecomp.sdc.be.distribution.api.client.RegistrationRequest.class), description = "json describe the artifact")}) @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) public Response unRegisterForDistribution( - @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, - @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter( hidden = true) String requestJson) { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "Length of the request body", required = true) @HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(hidden = true) String requestJson) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - Wrapper responseWrapper = new Wrapper<>(); Wrapper unRegistrationRequestWrapper = new Wrapper<>(); - validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL); - if (responseWrapper.isEmpty()) { validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson); } @@ -341,65 +289,67 @@ public class DistributionServlet extends BeGenericServlet { validateEnv(responseWrapper); } if (responseWrapper.isEmpty()) { - distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement())); + distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), + buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement())); } else { - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(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) { - // 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)); + 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)); + Response missingHeaderResponse = buildErrorResponse( + distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); responseWrapper.setInnerElement(missingHeaderResponse); } } - } 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)); + Response missingHeaderResponse = buildErrorResponse( + distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID)); responseWrapper.setInnerElement(missingHeaderResponse); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); getComponentsUtils().auditMissingInstanceIdAsDistributionEngineEvent(auditingAction, responseFormat.getStatus().toString()); - } - } private void validateJson(Wrapper responseWrapper, Wrapper registrationRequestWrapper, String requestJson) { if (requestJson == null || requestJson.isEmpty()) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); + 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)); + 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)); + 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)); + Response missingBodyResponse = buildErrorResponse( + distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); responseWrapper.setInnerElement(missingBodyResponse); } } - } private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest 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 index 69b50e0aa0..c67594f275 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.dto; import com.fasterxml.jackson.annotation.JsonInclude; @@ -34,7 +33,7 @@ import lombok.Setter; @Getter @Setter public class ExternalRefDTO { + @JsonInclude private String 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 783d1fc754..636c7ce140 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.ecomp; import fj.data.Either; @@ -49,10 +48,11 @@ import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; public class EcompIntImpl implements IPortalRestAPIService { - private static final String FAILED_TO_CONVERT_ROLES = "Failed to convert Roles"; + public static final String FAILED_TO_GET_ROLES = "Failed to get Roles"; - private static final String GET_USER_ROLES = "GetUserRoles"; public static final String ERROR_FAILED_TO_GET_ROLES = "Error: Failed to get Roles"; + private static final String FAILED_TO_CONVERT_ROLES = "Failed to convert Roles"; + private static final String GET_USER_ROLES = "GetUserRoles"; private static final String PUSH_USER_ROLE = "PushUserRole"; private static final String FAILED_TO_FETCH_ROLES = "Failed to fetch roles"; private static final String FAILED_TO_CONVERT_USER2 = "Failed to convert User {}"; @@ -79,17 +79,13 @@ public class EcompIntImpl implements IPortalRestAPIService { log.debug("Start handle request of ECOMP pushUser"); try { if (user == null) { - BeEcompErrorManager.getInstance() - .logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, ErrorSeverity.INFO); log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER); throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER); } - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - final String modifierAttId = JH0003; log.debug("modifier id is {}", modifierAttId); - User convertedAsdcUser = EcompUserConverter.convertEcompUserToUser(user); userBusinessLogic.createUser(modifierAttId, convertedAsdcUser); log.debug("User created {}", user); @@ -98,14 +94,12 @@ public class EcompIntImpl implements IPortalRestAPIService { log.debug("User already exist {}", user); } else { log.debug(FAILED_TO_CREATE_USER, user); - BeEcompErrorManager.getInstance() - .logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, ErrorSeverity.ERROR); throw new PortalAPIException(FAILED_TO_CREATE_USER + ce.getActionStatus()); } } catch (Exception e) { log.debug(FAILED_TO_CREATE_USER, user, e); - BeEcompErrorManager.getInstance() - .logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, ErrorSeverity.ERROR); throw new PortalAPIException(FAILED_TO_CREATE_USER, e); } } @@ -120,46 +114,35 @@ public class EcompIntImpl implements IPortalRestAPIService { @Override public void editUser(String loginId, EcompUser user) throws PortalAPIException { log.debug("Start handle request of ECOMP editUser"); - try { if (user == null) { log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER); - BeEcompErrorManager.getInstance() - .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, ErrorSeverity.INFO); throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER); } else if (loginId == null) { log.debug(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID); - BeEcompErrorManager.getInstance() - .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, ErrorSeverity.INFO); throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID); } - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) { log.debug("loginId and user loginId not equal"); - BeEcompErrorManager.getInstance() - .logInvalidInputError(EDIT_USER, "loginId and user loginId not equal", ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, "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); } - User asdcUser = EcompUserConverter.convertEcompUserToUser(user); - Either updateUserCredentialsResponse = - userBusinessLogic.updateUserCredentials(asdcUser); - + Either updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser); if (updateUserCredentialsResponse.isRight()) { log.debug(FAILED_TO_UPDATE_USER_CREDENTIALS); - BeEcompErrorManager.getInstance() - .logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS, ErrorSeverity.ERROR); throw new PortalAPIException(FAILED_TO_EDIT_USER + updateUserCredentialsResponse.right().value()); } } catch (Exception e) { log.debug(FAILED_TO_UPDATE_USER_CREDENTIALS); throw new PortalAPIException(FAILED_TO_EDIT_USER, e); } - } @Override @@ -168,8 +151,7 @@ public class EcompIntImpl implements IPortalRestAPIService { try { if (loginId == null) { log.debug(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID); - BeEcompErrorManager.getInstance() - .logInvalidInputError(GET_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, ErrorSeverity.INFO); throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID); } UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); @@ -179,15 +161,13 @@ public class EcompIntImpl implements IPortalRestAPIService { return ecompUser.left().value(); } else { log.debug(FAILED_TO_GET_USER); - BeEcompErrorManager.getInstance() - .logInvalidInputError(GET_USER, FAILED_TO_GET_USER, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER, FAILED_TO_GET_USER, ErrorSeverity.INFO); throw new PortalAPIException(ecompUser.right().value()); } } catch (ComponentException ce) { log.debug(FAILED_TO_GET_USER); BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER, FAILED_TO_GET_USER, ErrorSeverity.INFO); throw new PortalAPIException(FAILED_TO_GET_USER + ce.getActionStatus()); - } catch (Exception e) { log.debug(FAILED_TO_GET_USER); throw new PortalAPIException(FAILED_TO_GET_USER, e); @@ -197,7 +177,6 @@ public class EcompIntImpl implements IPortalRestAPIService { @Override public List getUsers() throws PortalAPIException { log.debug("Start handle request of ECOMP getUsers"); - try { UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); List users = userBusinessLogic.getUsersList(JH0003, null, null); @@ -207,8 +186,7 @@ public class EcompIntImpl implements IPortalRestAPIService { if (ecompUser.isRight() || ecompUser.left().value() == null) { log.debug(FAILED_TO_CONVERT_USER2, user); BeEcompErrorManager.getInstance() - .logInvalidInputError(GET_USERS, "Failed to convert User" + user.toString(), - ErrorSeverity.WARNING); + .logInvalidInputError(GET_USERS, "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); continue; } ecompUserList.add(ecompUser.left().value()); @@ -232,19 +210,15 @@ public class EcompIntImpl implements IPortalRestAPIService { 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); + BeEcompErrorManager.getInstance().logInvalidInputError("GetAvailableRoles", FAILED_TO_FETCH_ROLES, ErrorSeverity.INFO); throw new PortalAPIException("Roles fetching failed", e); } - } /** @@ -253,14 +227,10 @@ public class EcompIntImpl implements IPortalRestAPIService { @Override public void pushUserRole(String loginId, List roles) throws PortalAPIException { log.debug("Start handle request of ECOMP pushUserRole"); - final String modifierAttId = JH0003; log.debug("modifier id is {}", modifierAttId); - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - String updatedRole; - if (roles == null) { throw new PortalAPIException("Error: Received null for roles"); } else if (roles.iterator().hasNext()) { @@ -271,21 +241,18 @@ public class EcompIntImpl implements IPortalRestAPIService { userBusinessLogic.updateUserRole(modifierAttId, loginId, updatedRole); } catch (Exception e) { log.debug("Error: Failed to update role"); - BeEcompErrorManager.getInstance() - .logInvalidInputError(PUSH_USER_ROLE, "Failed to update role", ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER_ROLE, "Failed to update role", ErrorSeverity.INFO); throw new PortalAPIException("Failed to update role" + e); } } else { log.debug("Error: No roles in List"); - BeEcompErrorManager.getInstance() - .logInvalidInputError(PUSH_USER_ROLE, FAILED_TO_FETCH_ROLES, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER_ROLE, FAILED_TO_FETCH_ROLES, ErrorSeverity.INFO); //in this cases we want to deactivate the user try { getUserBusinessLogicExt().deActivateUser(modifierAttId, loginId); } catch (Exception e) { log.debug("Error: Failed to deactivate user {}", loginId); - BeEcompErrorManager.getInstance() - .logInvalidInputError(PUSH_USER_ROLE, "Failed to deactivate user", ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER_ROLE, "Failed to deactivate user", ErrorSeverity.INFO); throw new PortalAPIException("Error: Failed to deactivate user" + e); } } @@ -300,41 +267,34 @@ public class EcompIntImpl implements IPortalRestAPIService { Either ecompUser = EcompUserConverter.convertUserToEcompUser(user); if (ecompUser.isRight()) { log.debug("Error: Failed to convert Roles"); - BeEcompErrorManager.getInstance() - .logInvalidInputError(GET_USER_ROLES, FAILED_TO_CONVERT_ROLES, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER_ROLES, 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(GET_USER_ROLES, FAILED_TO_CONVERT_ROLES, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER_ROLES, FAILED_TO_CONVERT_ROLES, ErrorSeverity.ERROR); throw new PortalAPIException(); } return new LinkedList<>(ecompUser.left().value().getRoles()); } catch (ComponentException ce) { log.debug(ERROR_FAILED_TO_GET_ROLES); - BeEcompErrorManager.getInstance() - .logInvalidInputError(GET_USER_ROLES, FAILED_TO_GET_ROLES, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER_ROLES, FAILED_TO_GET_ROLES, ErrorSeverity.INFO); throw new PortalAPIException(FAILED_TO_GET_ROLES + ce.getActionStatus()); } catch (Exception e) { log.debug(ERROR_FAILED_TO_GET_ROLES); - BeEcompErrorManager.getInstance() - .logInvalidInputError(GET_USER_ROLES, FAILED_TO_GET_ROLES, ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER_ROLES, FAILED_TO_GET_ROLES, ErrorSeverity.INFO); throw new PortalAPIException(FAILED_TO_GET_ROLES, e); } } @Override - public boolean isAppAuthenticated(HttpServletRequest request, Map appCredentials) - throws PortalAPIException { + public boolean isAppAuthenticated(HttpServletRequest request, Map appCredentials) throws PortalAPIException { final String portal_key = PortalApiProperties.getProperty("portal_pass"); final String portal_user = PortalApiProperties.getProperty("portal_user"); final String username = request.getHeader("username"); final String password = request.getHeader("password"); - if (username != null && password != null) { try { - if (username.equals(CipherUtil.decryptPKC(portal_user)) - && password.equals(CipherUtil.decryptPKC(portal_key))) { + if (username.equals(CipherUtil.decryptPKC(portal_user)) && password.equals(CipherUtil.decryptPKC(portal_key))) { log.debug("User authenticated - Username: {}", username); return true; } @@ -358,13 +318,10 @@ public class EcompIntImpl implements IPortalRestAPIService { } /** - * 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 - * appropriate response to Portal. - * However, the app can always choose to have a custom implementation of - * this method. For Open-source implementation, for example, the app will - * have a totally different implementation for this method. + * 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 appropriate response to Portal. However, the app can always choose + * to have a custom implementation of this method. For Open-source implementation, for example, the app will have a totally different + * implementation for this method. * * @param request The HttpServletRequest * @return true if the request contains appropriate credentials, else false. diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalPropertiesEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalPropertiesEnum.java index b8ecbacff8..ddbbc92d2a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalPropertiesEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalPropertiesEnum.java @@ -17,16 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.ecomp; public enum PortalPropertiesEnum { - APP_NAME("portal_app_name"), - ECOMP_REST_URL("ecomp_rest_url"), - PASSWORD("portal_pass"), - UEB_APP_KEY("ueb_app_key"), - USER("portal_user"); - + APP_NAME("portal_app_name"), ECOMP_REST_URL("ecomp_rest_url"), PASSWORD("portal_pass"), UEB_APP_KEY("ueb_app_key"), USER("portal_user"); private final String value; PortalPropertiesEnum(String value) { @@ -36,4 +30,4 @@ public enum PortalPropertiesEnum { public String value() { return value; } -} \ No newline at end of file +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalRestApiCentralServiceImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalRestApiCentralServiceImpl.java index 757eeb83ce..55ce879bde 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalRestApiCentralServiceImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalRestApiCentralServiceImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.ecomp; import fj.data.Either; @@ -44,6 +43,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; public final class PortalRestApiCentralServiceImpl implements IPortalRestCentralService { + private static final String FAILED_TO_UPDATE_USER_CREDENTIALS = "Failed to update user credentials"; private static final String FAILED_TO_DEACTIVATE_USER = "Failed to deactivate user {}"; private static final String FAILED_TO_EDIT_USER = "Failed to edit user"; @@ -69,8 +69,8 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral userBusinessLogicExt = (UserBusinessLogicExt) ctx.getBean("userBusinessLogicExt"); } catch (Exception e) { log.debug("Failed to get user UserBusinessLogic", e); - BeEcompErrorManager.getInstance().logInvalidInputError("constructor", "Exception thrown" + e.getMessage(), - BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInvalidInputError("constructor", "Exception thrown" + e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR); throw new PortalAPIException("SDC Internal server error"); } log.debug("PortalRestApiCentralServiceImpl Class Instantiated"); @@ -82,6 +82,18 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral this.userBusinessLogicExt = uble; } + public static void checkIfSingleRoleProvided(EcompUser user) throws PortalAPIException { + if (user.getRoles() == null) { + log.debug(RECEIVED_NULL_ROLES, user); + BeEcompErrorManager.getInstance().logInvalidInputError(CHECK_ROLES, RECEIVED_NULL_ROLES, BeEcompErrorManager.ErrorSeverity.ERROR); + throw new PortalAPIException(RECEIVED_NULL_ROLES + user); + } else if (user.getRoles().size() > 1) { + log.debug(RECEIVED_MULTIPLE_ROLES, user); + BeEcompErrorManager.getInstance().logInvalidInputError(CHECK_ROLES, RECEIVED_MULTIPLE_ROLES2, BeEcompErrorManager.ErrorSeverity.ERROR); + throw new PortalAPIException(RECEIVED_MULTIPLE_ROLES2 + user); + } + } + @Override public Map getAppCredentials() throws PortalAPIException { Map credMap = new HashMap<>(); @@ -103,30 +115,24 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral @Override public void pushUser(EcompUser user) throws PortalAPIException { log.debug("Start handle request of ECOMP pushUser"); - if (user == null) { - BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, - BeEcompErrorManager.ErrorSeverity.INFO); + BeEcompErrorManager.getInstance() + .logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, BeEcompErrorManager.ErrorSeverity.INFO); log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER); throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER); } checkIfSingleRoleProvided(user); - final String modifierAttId = JH0003; log.debug("modifier id is {}", modifierAttId); - User convertedAsdcUser = EcompUserConverter.convertEcompUserToUser(user); - try { log.debug("Before creating ecomp user {} sdc user {}", user, convertedAsdcUser); userBusinessLogic.createUser(modifierAttId, convertedAsdcUser); } catch (Exception e) { log.debug(FAILED_TO_CREATE_USER, user, e); - BeEcompErrorManager.getInstance() - .logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, BeEcompErrorManager.ErrorSeverity.ERROR); throw new PortalAPIException(FAILED_TO_CREATE_USER + e.getMessage()); } - log.debug("User created ecomp user {} sdc user {}", user, convertedAsdcUser); } @@ -134,31 +140,26 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral public void editUser(String loginId, EcompUser user) throws PortalAPIException { if (user == null) { log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER); - BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, - BeEcompErrorManager.ErrorSeverity.INFO); + BeEcompErrorManager.getInstance() + .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, BeEcompErrorManager.ErrorSeverity.INFO); throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER); } else if (loginId == null) { log.debug(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID); - BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, - BeEcompErrorManager.ErrorSeverity.INFO); + BeEcompErrorManager.getInstance() + .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, BeEcompErrorManager.ErrorSeverity.INFO); throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID); } - - log.debug("Start handle request of ECOMP editUser {} with loginId {} with follopwing roles {}", user, loginId, - user.getRoles()); - + log.debug("Start handle request of ECOMP editUser {} with loginId {} with follopwing roles {}", user, loginId, user.getRoles()); final String modifierAttId = JH0003; log.debug("modifier id is {}", modifierAttId); - if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) { log.debug("loginId and user loginId not equal"); - BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, "loginId and user loginId not equal", - BeEcompErrorManager.ErrorSeverity.INFO); + BeEcompErrorManager.getInstance() + .logInvalidInputError(EDIT_USER, "loginId and user loginId not equal", BeEcompErrorManager.ErrorSeverity.INFO); throw new PortalAPIException("loginId not equals to the user loginId field"); } else if (user.getLoginId() == null) { user.setLoginId(loginId); } - Either verifyNewUser; try { verifyNewUser = userBusinessLogic.verifyNewUserForPortal(user.getLoginId()); @@ -166,26 +167,21 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral log.debug("Failed to verify new user", e); throw new PortalAPIException(e.getCause()); } - - if (verifyNewUser.isRight() - && (ActionStatus.USER_NOT_FOUND.equals(verifyNewUser.right().value()) - || ActionStatus.USER_INACTIVE.equals(verifyNewUser.right().value()))) { + if (verifyNewUser.isRight() && (ActionStatus.USER_NOT_FOUND.equals(verifyNewUser.right().value()) || ActionStatus.USER_INACTIVE + .equals(verifyNewUser.right().value()))) { log.debug("Edit user for user that not exist in DB, executing push user flow {}", user); pushUser(user); return; } - User asdcUser = EcompUserConverter.convertEcompUserToUser(user); log.debug("Before editing ecomp user {} sdc user {}", user, asdcUser); Either updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser); - if (updateUserCredentialsResponse.isRight()) { log.debug(FAILED_TO_UPDATE_USER_CREDENTIALS); - BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS, - BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS, BeEcompErrorManager.ErrorSeverity.ERROR); throw new PortalAPIException(FAILED_TO_EDIT_USER + updateUserCredentialsResponse.right().value()); } - if (user.getRoles() == null || user.getRoles().isEmpty()) { try { log.debug("Before deactivating ecomp user {} sdc user {}", user, asdcUser); @@ -193,8 +189,7 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral } catch (Exception e) { log.debug("Error: Failed to deactivate user {}", loginId); BeEcompErrorManager.getInstance() - .logInvalidInputError(FAILED_TO_DEACTIVATE_USER, "Failed to deactivate user", - BeEcompErrorManager.ErrorSeverity.INFO); + .logInvalidInputError(FAILED_TO_DEACTIVATE_USER, "Failed to deactivate user", BeEcompErrorManager.ErrorSeverity.INFO); throw new PortalAPIException("Error: Failed to deactivate user" + e); } } else { @@ -205,8 +200,7 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral } catch (Exception e) { log.debug("Error: Failed to update user role {}", loginId); BeEcompErrorManager.getInstance() - .logInvalidInputError(FAILED_TO_EDIT_USER, "Failed to update user role", - BeEcompErrorManager.ErrorSeverity.INFO); + .logInvalidInputError(FAILED_TO_EDIT_USER, "Failed to update user role", BeEcompErrorManager.ErrorSeverity.INFO); throw new PortalAPIException("Error: Failed to update user role" + e); } } @@ -218,27 +212,10 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral String header = request.getHeader(Constants.USER_ID_HEADER); if (header == null) { log.debug(FAILED_TO_GET_USER_ID_HEADER); - BeEcompErrorManager.getInstance().logInvalidInputError("getUserId", FAILED_TO_GET_USER_ID_HEADER, - BeEcompErrorManager.ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance() + .logInvalidInputError("getUserId", FAILED_TO_GET_USER_ID_HEADER, BeEcompErrorManager.ErrorSeverity.ERROR); throw new PortalAPIException(FAILED_TO_GET_USER_ID_HEADER); } return header; } - - - public static void checkIfSingleRoleProvided(EcompUser user) throws PortalAPIException { - if (user.getRoles() == null) { - log.debug(RECEIVED_NULL_ROLES, user); - BeEcompErrorManager.getInstance() - .logInvalidInputError(CHECK_ROLES, RECEIVED_NULL_ROLES, BeEcompErrorManager.ErrorSeverity.ERROR); - throw new PortalAPIException(RECEIVED_NULL_ROLES + user); - } else if (user.getRoles().size() > 1) { - log.debug(RECEIVED_MULTIPLE_ROLES, user); - BeEcompErrorManager.getInstance().logInvalidInputError(CHECK_ROLES, RECEIVED_MULTIPLE_ROLES2, - BeEcompErrorManager.ErrorSeverity.ERROR); - throw new PortalAPIException(RECEIVED_MULTIPLE_ROLES2 + user); - } - } - - } 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 0729ee28c6..0d43082dc4 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 @@ -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. @@ -17,10 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.ecomp.converters; import fj.data.Either; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -46,31 +50,24 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - @org.springframework.stereotype.Component("asset-metadata-utils") public class AssetMetadataConverter { - private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class); - - @Autowired - private ComponentsUtils componentsUtils; + private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class); @Autowired protected ToscaOperationFacade toscaOperationFacade; + @Autowired + private ComponentsUtils componentsUtils; /* * 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) { + 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()) { @@ -78,40 +75,30 @@ public class AssetMetadataConverter { } retResList.add(resMetaData.left().value()); } - return Either.left(retResList); - } - public Either convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { + 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{ + } else { return Either.left(resMetaData.left().value()); } - } - private Either convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { - + 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); - - default: - - ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); - return Either.right(responseFormat); + case RESOURCE: + return generateResourceMeatdata(serverBaseURL, detailed, curr); + case SERVICE: + return generateServiceMetadata(serverBaseURL, detailed, curr); + default: + ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); + return Either.right(responseFormat); } } @@ -119,56 +106,53 @@ public class AssetMetadataConverter { 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); + 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; + 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); + Either converted = convertToServiceDetailedMetadata( + (ServiceAssetDetailedMetadata) metaData, (Service) curr); 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); } @@ -183,13 +167,13 @@ public class AssetMetadataConverter { String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); asset.setToscaModelURL(toscaModelUrl); } - return asset; } - private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { + private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, + boolean detailed) { assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); - if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ + if (resource.getCategories() != null && !resource.getCategories().isEmpty()) { CategoryDefinition categoryDefinition = resource.getCategories().get(0); assetToPopulate.setCategory(categoryDefinition.getName()); assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().get(0).getName()); @@ -197,94 +181,81 @@ public class AssetMetadataConverter { 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) { + private T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, + boolean detailed) { assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); - - if(service.getCategories() != null && !service.getCategories().isEmpty()){ + 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) { - + 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()); + 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, deploymentArtifacts); - assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); assetToPopulate.setDescription(resource.getDescription()); return Either.left(assetToPopulate); } - private Either convertToServiceDetailedMetadata(T assetToPopulate, Service service) { - + private Either convertToServiceDetailedMetadata(T assetToPopulate, + Service service) { List componentInstances = service.getComponentInstances(); - if (componentInstances != null) { - Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); + 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, Map artifacts) { - + private T populateResourceWithArtifacts(T asset, Resource resource, + Map artifacts) { List artifactMetaList = populateAssetWithArtifacts(resource, artifacts); - asset.setArtifacts(artifactMetaList); - return asset; } - private T populateServiceWithArtifacts(T asset, Service service, Map artifacts) { - + 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<>(); + 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); + ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, + ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); artifactMetaList.add(convertedArtifactMetadata); } } @@ -292,22 +263,19 @@ public class AssetMetadataConverter { return artifactMetaList.isEmpty() ? null : artifactMetaList; } - private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { + 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.setArtifactURL( + String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); } - metadata.setArtifactDescription(artifact.getDescription()); metadata.setArtifactTimeout(artifact.getTimeout() != null && artifact.getTimeout() > 0 ? artifact.getTimeout() : null); metadata.setArtifactChecksum(artifact.getArtifactChecksum()); @@ -319,15 +287,14 @@ public class AssetMetadataConverter { return metadata; } - private Either, StorageOperationStatus> convertToResourceInstanceMetadata(List componentInstances, String componentType, String componentUUID) { + 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()) { @@ -342,21 +309,20 @@ public class AssetMetadataConverter { } } else { invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); - resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); + 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())){ + 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()); + ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, + componentInstance.getNormalizedName()); artifactMetaList.add(converted); } metadata.setArtifacts(artifactMetaList); @@ -365,5 +331,4 @@ public class AssetMetadataConverter { } return Either.left(retList); } - } 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 d7beb14c7b..df8e97f9a9 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.ecomp.converters; import org.onap.portalsdk.core.onboarding.exception.PortalAPIException; @@ -27,6 +26,7 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.log.wrappers.Logger; public final class EcompRoleConverter { + private static final String FAILED_TO_CONVERT_USER = "Failed to convert user"; private static final String EDIT_USER = "EditUser"; private static final Logger log = Logger.getLogger(EcompRoleConverter.class); @@ -35,16 +35,14 @@ public final class EcompRoleConverter { } public static String convertEcompRoleToRole(EcompRole ecompRole) throws PortalAPIException { - log.debug("converting role{}", ecompRole); if (ecompRole == null) { log.debug("recieved null for roles"); return null; } - for (Role role : Role.values()) { - if (role.name().toLowerCase().equals(ecompRole.getName().toLowerCase())){ - return role.name(); + if (role.name().toLowerCase().equals(ecompRole.getName().toLowerCase())) { + return role.name(); } } BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, FAILED_TO_CONVERT_USER, BeEcompErrorManager.ErrorSeverity.INFO); 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 ce23c6e368..0fb42d2d20 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.ecomp.converters; import fj.data.Either; @@ -38,23 +37,19 @@ public final class 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())) { @@ -63,47 +58,37 @@ public final class EcompUserConverter { break; } } - Set convertedRoleSet = new HashSet<>(); convertedRoleSet.add(convertedRole); convertedUser.setRoles(convertedRoleSet); - return Either.left(convertedUser); } public static User convertEcompUserToUser(EcompUser ecompUser) throws PortalAPIException { User convertedUser = new User(); - if (ecompUser == null) { throw new PortalAPIException("ecomp user is null"); } - convertedUser.setFirstName(ecompUser.getFirstName()); convertedUser.setLastName(ecompUser.getLastName()); - if (ecompUser.getLoginId() != null && !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 convertedUser; } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/RestrictionAccessFilterException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/RestrictionAccessFilterException.java index a25bf1a505..c92779f75c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/RestrictionAccessFilterException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/RestrictionAccessFilterException.java @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.exception; -public class RestrictionAccessFilterException extends RuntimeException{ - +public class RestrictionAccessFilterException extends RuntimeException { + public RestrictionAccessFilterException(Exception exception) { super(exception); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.java index b47d355e47..f8936b190a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.exception; import org.openecomp.sdc.be.dao.api.ActionStatus; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java index 66357c118e..d38f08f376 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.exception; public class ToscaExportException extends Exception { @@ -24,5 +23,4 @@ public class ToscaExportException extends Exception { public ToscaExportException(String message) { super(message); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServlet.java index 6b24867ad5..17819de71e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServlet.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.externalapi.servlet; import com.jcabi.aspects.Loggable; @@ -26,18 +25,25 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.tags.Tag; - import java.io.IOException; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; +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 org.openecomp.sdc.be.components.impl.*; +import org.openecomp.sdc.be.components.impl.AbstractTemplateBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +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.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; @@ -48,11 +54,14 @@ import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractTemplateI import org.openecomp.sdc.be.externalapi.servlet.representation.CopyServiceInfo; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; -import org.openecomp.sdc.be.model.*; +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.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo; -import org.openecomp.sdc.be.servlets.*; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; +import org.openecomp.sdc.be.servlets.RepresentationUtils; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.elements.LoggerSupportability; @@ -67,33 +76,27 @@ import org.springframework.stereotype.Controller; * * @author hekeguang */ - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Tag(name = "SDC External APIs") @Server(url = "/sdc") @Controller - public class AbstractTemplateServlet extends AbstractValidationsServlet { - @Context - private HttpServletRequest request; - + private static final Logger log = Logger.getLogger(AbstractTemplateServlet.class); + private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(AbstractTemplateServlet.class.getName()); private final ElementBusinessLogic elementBusinessLogic; private final AbstractTemplateBusinessLogic abstractTemplateBusinessLogic; - private final ServiceBusinessLogic serviceBusinessLogic; private final ResourceBusinessLogic resourceBusinessLogic; - - private static final Logger log = Logger.getLogger(AbstractTemplateServlet.class); - private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(AbstractTemplateServlet.class.getName()); + @Context + private HttpServletRequest request; @Inject - public AbstractTemplateServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, - ServletUtils servletUtils, ResourceImportManager resourceImportManager, - ElementBusinessLogic elementBusinessLogic, - AbstractTemplateBusinessLogic abstractTemplateBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) { + public AbstractTemplateServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, + ElementBusinessLogic elementBusinessLogic, AbstractTemplateBusinessLogic abstractTemplateBusinessLogic, + ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.elementBusinessLogic = elementBusinessLogic; this.abstractTemplateBusinessLogic = abstractTemplateBusinessLogic; @@ -112,39 +115,26 @@ public class AbstractTemplateServlet extends AbstractValidationsServlet { @GET @Path("/abstract/service/serviceUUID/{uuid}/status") @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Fetch abstract status of service", method = "GET", - summary = "Return whether the service is a virtual service", responses = {@ApiResponse(responseCode = "200", - description = "The check result of whether the service is an abstract service is returned", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", - description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + @Operation(description = "Fetch abstract status of service", method = "GET", summary = "Return whether the service is a virtual service", responses = { + @ApiResponse(responseCode = "200", description = "The check result of whether the service is an abstract service is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) @PermissionAllowed(AafPermission.PermNames.READ_VALUE) public Response getServiceAbstractStatus( - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The requested asset uuid", - required = true) @PathParam("uuid") final String uuid) throws IOException { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException { ResponseFormat responseFormat = null; AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TEMPLATE_ABSTRACT_STATUS; String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; log.debug("getServiceAbstractStatus: Start handle request of {}", url); - String assetType = "services"; ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue()); @@ -153,39 +143,31 @@ public class AbstractTemplateServlet extends AbstractValidationsServlet { if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { log.debug("getServiceAbstractStatus: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildErrorResponse(responseFormat); } - try { - - Either, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); - + Either, ResponseFormat> assetTypeData = elementBusinessLogic + .getCatalogComponentsByUuidAndAssetType(assetType, uuid); if (assetTypeData.isRight()) { log.debug("getServiceAbstractStatus: Service Fetching Failed"); responseFormat = assetTypeData.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); - + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildErrorResponse(responseFormat); } resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName()); log.debug("getServiceAbstractStatus: Service Fetching Success"); - Either resMetadata = abstractTemplateBusinessLogic.getServiceAbstractStatus(assetTypeData.left().value()); + Either resMetadata = abstractTemplateBusinessLogic + .getServiceAbstractStatus(assetTypeData.left().value()); if (resMetadata.isRight()) { log.debug("getServiceAbstractStatus: Service abstract status get Failed"); responseFormat = resMetadata.right().value(); - - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildErrorResponse(responseFormat); } Object result = RepresentationUtils.toRepresentation(resMetadata.left().value()); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); - + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildOkResponse(responseFormat, result); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch abstract status of service"); @@ -205,63 +187,44 @@ public class AbstractTemplateServlet extends AbstractValidationsServlet { @POST @Path("/abstract/service/serviceUUID/{uuid}/copy") @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Copy a new service based on the existing service", method = "POST", - summary = "Return whether the copy service is successful", responses = {@ApiResponse(responseCode = "200", - description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", - description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(responseCode = "409", description = "Service already exist")}) + @Operation(description = "Copy a new service based on the existing service", method = "POST", summary = "Return whether the copy service is successful", responses = { + @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(responseCode = "409", description = "Service already exist")}) @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE) public Response copyExistService( - @Parameter(description = "The user id", - required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The requested asset uuid", - required = true) @PathParam("uuid") final String uuid, - @Parameter(hidden = true) String data) throws IOException { - - + @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid, + @Parameter(hidden = true) String data) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("copyExistService: Start handle request of {}", url); User modifier = new User(); modifier.setUserId(userId); log.debug("modifier id is {}", userId); loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, StatusCode.STARTED, "Starting to create a service by user {} ", userId); - validateNotEmptyBody(data); - Either convertResponse = parseToCopyServiceInfo(data, modifier); if (convertResponse.isRight()) { throw new ByResponseFormatComponentException(convertResponse.right().value()); } - String assetType = "services"; CopyServiceInfo copyServiceInfo = convertResponse.left().value(); - Either, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); - + Either, ResponseFormat> assetTypeData = elementBusinessLogic + .getCatalogComponentsByUuidAndAssetType(assetType, uuid); if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) { log.debug("getServiceAbstractStatus: Service Fetching Failed"); throw new ByResponseFormatComponentException(assetTypeData.right().value()); } - log.debug("getServiceAbstractStatus: Service Fetching Success"); - Service service = (Service) assetTypeData.left().value().get(0); List tags = service.getTags(); if (tags != null && !tags.isEmpty()) { @@ -275,20 +238,17 @@ public class AbstractTemplateServlet extends AbstractValidationsServlet { service.setName(copyServiceInfo.getNewServiceName()); tags.add(copyServiceInfo.getNewServiceName()); Either actionResponse = serviceBusinessLogic.createService(service, modifier); - if (actionResponse.isRight()) { log.debug("Failed to create service"); throw new ByResponseFormatComponentException(actionResponse.right().value()); } - - loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, "Service {} has been copyied by user {} ", service.getName(), userId); - + loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Service {} has been copyied by user {} ", service.getName(), userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); - } public Either parseToCopyServiceInfo(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, CopyServiceInfo.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, CopyServiceInfo.class, AuditingActionEnum.CREATE_RESOURCE, + ComponentTypeEnum.SERVICE); } - } 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 3955fdd519..f4615ab9c5 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet; import com.jcabi.aspects.Loggable; @@ -79,7 +78,6 @@ import org.springframework.stereotype.Controller; * This Servlet serves external users operations on artifacts. * * @author mshitrit - * */ @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @@ -90,21 +88,16 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { private static final String FAILED_TO_UPDATE_ARTIFACT = "failed to update artifact"; private static final String DOUBLE_CURLY_BRACKETS = "{} {}"; - - @Context - private HttpServletRequest request; - - private final ArtifactsBusinessLogic artifactsBusinessLogic; - private static final Logger log = Logger.getLogger(ArtifactExternalServlet.class); - private static String startLog = "Start handle request of "; + private final ArtifactsBusinessLogic artifactsBusinessLogic; + @Context + private HttpServletRequest request; @Inject - public ArtifactExternalServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, - ServletUtils servletUtils, ResourceImportManager resourceImportManager, - ArtifactsBusinessLogic artifactsBusinessLogic) { + public ArtifactExternalServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, + ArtifactsBusinessLogic artifactsBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.artifactsBusinessLogic = artifactsBusinessLogic; } @@ -112,57 +105,36 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @POST @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}") @Produces(MediaType.APPLICATION_JSON) - @Operation(parameters = {@Parameter(required = true, - schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class))}, - description = "uploads of artifact to VF operation workflow", method = "POST", - summary = "uploads of artifact to VF operation workflow", responses = { - @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(responseCode = "400", - description = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(responseCode = "400", - description = "Artifact name given in input already exists in the context of the asset - SVC4125"), - @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), - @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), - @ApiResponse(responseCode = "400", - description = "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(responseCode = "400", - description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @Operation(parameters = { + @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class))}, description = "uploads of artifact to VF operation workflow", method = "POST", summary = "uploads of artifact to VF operation workflow", responses = { + @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"), + @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), + @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), + @ApiResponse(responseCode = "400", description = "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(responseCode = "400", description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) public Response uploadInterfaceOperationArtifact( - @Parameter(description = "Determines the format of the body of the request", - required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, - @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", - required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "Asset type") @PathParam("assetType") String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter(description = "The uuid of the interface", - required = true) @PathParam("interfaceUUID") final String interfaceUUID, - @Parameter(description = "The uuid of the operation", - required = true) @PathParam("operationUUID") final String operationUUID, - @Parameter(description = "The uuid of the artifact", - required = true) @PathParam("artifactUUID") final String artifactUUID, - @Parameter(hidden = true) String data) { + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, + @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "Asset type") @PathParam("assetType") String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "The uuid of the interface", required = true) @PathParam("interfaceUUID") final String interfaceUUID, + @Parameter(description = "The uuid of the operation", required = true) @PathParam("operationUUID") final String operationUUID, + @Parameter(description = "The uuid of the artifact", required = true) @PathParam("artifactUUID") final String artifactUUID, + @Parameter(hidden = true) String data) { Wrapper responseWrapper = new Wrapper<>(); ResponseFormat responseFormat = null; String requestURI = request.getRequestURI(); @@ -170,7 +142,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { log.debug(DOUBLE_CURLY_BRACKETS, startLog, url); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(assetType); ArtifactDefinition artifactDefinition = null; - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { log.debug("updateArtifact: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); @@ -184,20 +155,21 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { try { if (responseWrapper.isEmpty()) { Either uploadArtifactEither = artifactsBusinessLogic - .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum - .findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID, - resourceCommonInfo, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); + .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum.findByParamName(assetType), uuid, + interfaceUUID, operationUUID, artifactUUID, resourceCommonInfo, + new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); if (uploadArtifactEither.isRight()) { log.debug(FAILED_TO_UPDATE_ARTIFACT); responseFormat = uploadArtifactEither.right().value(); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } else { - artifactDefinition=uploadArtifactEither.left().value(); + artifactDefinition = uploadArtifactEither.left().value(); Object representation = RepresentationUtils.toRepresentation(artifactDefinition); 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)); + responseWrapper + .setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); } } } catch (Exception e) { @@ -206,8 +178,9 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { log.debug(message, e); responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); } finally { - getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, - resourceCommonInfo, request, artifactDefinition, null); + getComponentsUtils() + .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, resourceCommonInfo, request, artifactDefinition, + null); } return responseWrapper.getInnerElement(); } @@ -218,56 +191,36 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @POST @Path("/{assetType}/{uuid}/artifacts") @Produces(MediaType.APPLICATION_JSON) - @Operation(parameters = {@Parameter(required = true, - schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class))}, - description = "uploads of artifact to a resource or service", method = "POST", - summary = "uploads of artifact to a resource or service", responses = { - @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(responseCode = "400", - description = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(responseCode = "400", - description = "Artifact name given in input already exists in the context of the asset - SVC4125"), - @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), - @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), - @ApiResponse(responseCode = "400", - description = "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(responseCode = "400", - description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @Operation(parameters = { + @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class))}, description = "uploads of artifact to a resource or service", method = "POST", summary = "uploads of artifact to a resource or service", responses = { + @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"), + @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), + @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), + @ApiResponse(responseCode = "400", description = "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(responseCode = "400", description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) @PermissionAllowed({AafPermission.PermNames.WRITE_VALUE}) public Response uploadArtifact( - @Parameter(description = "Determines the format of the body of the request", - required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", - required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type", - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter(hidden = true) String data) { - + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(schema = @Schema(allowableValues = { + "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(hidden = true) String data) { init(); - Wrapper responseWrapper = new Wrapper<>(); String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; @@ -275,7 +228,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); String componentTypeValue = componentType == null ? null : componentType.getValue(); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue); - if (componentType == null) { log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); @@ -283,15 +235,15 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { if (responseWrapper.isEmpty()) { validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); } - if (responseWrapper.isEmpty() ) { + if (responseWrapper.isEmpty()) { validateHttpCspUserIdHeader(userId, responseWrapper); } Response response = null; ArtifactDefinition artifactDefinition = null; try { if (responseWrapper.isEmpty()) { - artifactDefinition = artifactsBusinessLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, - resourceCommonInfo, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE)); + artifactDefinition = artifactsBusinessLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, resourceCommonInfo, + new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE)); Object representation = RepresentationUtils.toRepresentation(artifactDefinition); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); @@ -304,14 +256,15 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { log.debug(message, e); responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); response = buildErrorResponse(responseWrapper.getInnerElement()); - } catch (ComponentException e){ + } catch (ComponentException e) { responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(e)); - }finally { - if( response == null ){ + } finally { + if (response == null) { response = buildErrorResponse(responseWrapper.getInnerElement()); } - getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, - resourceCommonInfo, request, artifactDefinition, null); + getComponentsUtils() + .auditExternalCrudApi(responseWrapper.getInnerElement(), AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, resourceCommonInfo, request, + artifactDefinition, null); } return response; } @@ -322,56 +275,37 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @POST @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts") @Produces(MediaType.APPLICATION_JSON) - @Operation(parameters = {@Parameter(required = true, - schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), - description = "json describe the artifact")}, description = "uploads an artifact to a resource instance", - method = "POST", summary = "uploads an artifact to a resource instance", responses = { - @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(responseCode = "400", - description = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(responseCode = "400", - description = "Artifact name given in input already exists in the context of the asset - SVC4125"), - @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), - @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), - @ApiResponse(responseCode = "400", - description = "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(responseCode = "400", - description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @Operation(parameters = { + @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), description = "json describe the artifact")}, description = "uploads an artifact to a resource instance", method = "POST", summary = "uploads an artifact to a resource instance", responses = { + @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"), + @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), + @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), + @ApiResponse(responseCode = "400", description = "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(responseCode = "400", description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE) public Response uploadArtifactToInstance( - @Parameter(description = "Determines the format of the body of the request", - required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", - required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type", - required = true) @PathParam("assetType") final String assetType, - @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", - required = true) @PathParam("resourceInstanceName") final String resourceInstanceName, - @Parameter(hidden = true) String data) { - + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(schema = @Schema(allowableValues = { + "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType, + @Parameter(schema = @Schema(allowableValues = { + "resources,services"}), description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", required = true) @PathParam("resourceInstanceName") final String resourceInstanceName, + @Parameter(hidden = true) String data) { Wrapper responseWrapper = new Wrapper<>(); ResponseFormat responseFormat = null; String requestURI = request.getRequestURI(); @@ -381,7 +315,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { String componentTypeValue = componentType == null ? null : componentType.getValue(); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue); ArtifactDefinition artifactDefinition = null; - if (componentType == null) { log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -400,82 +333,62 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { try { if (responseWrapper.isEmpty()) { artifactDefinition = artifactsBusinessLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName, - new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE)); + new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE)); Object representation = RepresentationUtils.toRepresentation(artifactDefinition); 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 (IOException e) { + } catch (IOException e) { final String message = "failed to upload artifact to a resource instance"; BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); log.debug(message, e); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - }catch (ComponentException e){ + } catch (ComponentException e) { responseFormat = getComponentsUtils().getResponseFormat(e); throw e; - }finally { - getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, - resourceCommonInfo, request, artifactDefinition, null); + } finally { + getComponentsUtils() + .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, resourceCommonInfo, request, artifactDefinition, + null); } return responseWrapper.getInnerElement(); } - @POST @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") @Produces(MediaType.APPLICATION_JSON) - @Operation(parameters = {@Parameter(required = true, - schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), - description = "json describe the artifact")}, description = "updates an artifact on a resource or service", - method = "POST", summary = "uploads of artifact to a resource or service", responses = { - @ApiResponse(responseCode = "200", description = "Artifact updated", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(responseCode = "400", - description = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), - @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), - @ApiResponse(responseCode = "403", - description = "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(responseCode = "409", - description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @Operation(parameters = { + @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), description = "json describe the artifact")}, description = "updates an artifact on a resource or service", method = "POST", summary = "uploads of artifact to a resource or service", responses = { + @ApiResponse(responseCode = "200", description = "Artifact updated", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), + @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), + @ApiResponse(responseCode = "403", description = "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(responseCode = "409", description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE) public Response updateArtifact( - @Parameter(description = "Determines the format of the body of the request", - required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", - required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type", - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter( - description = "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, - @Parameter(hidden = true) String data) { - + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(schema = @Schema(allowableValues = { + "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "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, + @Parameter(hidden = true) String data) { Wrapper responseWrapper = new Wrapper<>(); ResponseFormat responseFormat = null; String requestURI = request.getRequestURI(); @@ -484,7 +397,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); String componentTypeValue = componentType == null ? null : componentType.getValue(); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue); - if (componentType == null) { log.debug("updateArtifact: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -503,8 +415,9 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { ArtifactDefinition artifactDefinition = null; try { if (responseWrapper.isEmpty()) { - artifactDefinition = artifactsBusinessLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, - resourceCommonInfo, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); + artifactDefinition = artifactsBusinessLogic + .updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, resourceCommonInfo, + new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); Object representation = RepresentationUtils.toRepresentation(artifactDefinition); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); @@ -517,13 +430,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { log.debug(message, e); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } catch (ComponentException e){ + } catch (ComponentException e) { responseFormat = getComponentsUtils().getResponseFormat(e); throw e; - } - finally{ - getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo, - request, artifactDefinition, artifactUUID); + } finally { + getComponentsUtils() + .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo, request, artifactDefinition, + artifactUUID); } return responseWrapper.getInnerElement(); } @@ -534,57 +447,36 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @POST @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") @Produces(MediaType.APPLICATION_JSON) - @Operation(parameters = {@Parameter(required = true, - schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), - description = "json describe the artifact")}, description = "updates an artifact on a resource instance", - method = "POST", summary = "uploads of artifact to a resource or service", responses = { - @ApiResponse(responseCode = "200", description = "Artifact updated", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(responseCode = "400", - description = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), - @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), - @ApiResponse(responseCode = "403", - description = "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(responseCode = "409", - description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @Operation(parameters = { + @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), description = "json describe the artifact")}, description = "updates an artifact on a resource instance", method = "POST", summary = "uploads of artifact to a resource or service", responses = { + @ApiResponse(responseCode = "200", description = "Artifact updated", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), + @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), + @ApiResponse(responseCode = "403", description = "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(responseCode = "409", description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE) public Response updateArtifactOnResourceInstance( - @Parameter(description = "Determines the format of the body of the request", - required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", - required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type", - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter( - description = "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, - @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", - required = true) @PathParam("resourceInstanceName") final String resourceInstanceName, - @Parameter(hidden = true) String data) { - + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum, + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(schema = @Schema(allowableValues = { + "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "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, + @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", required = true) @PathParam("resourceInstanceName") final String resourceInstanceName, + @Parameter(hidden = true) String data) { Wrapper responseWrapper = new Wrapper<>(); ResponseFormat responseFormat = null; String requestURI = request.getRequestURI(); @@ -593,7 +485,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); String componentTypeValue = componentType == null ? null : componentType.getValue(); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue); - if (componentType == null) { log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -609,11 +500,11 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - ArtifactDefinition artifactDefinition = null; try { if (responseWrapper.isEmpty()) { - artifactDefinition = artifactsBusinessLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, + artifactDefinition = artifactsBusinessLogic + .updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); Object representation = RepresentationUtils.toRepresentation(artifactDefinition); Map headers = new HashMap<>(); @@ -627,13 +518,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { log.debug(message, e); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } catch (ComponentException e){ + } catch (ComponentException e) { responseFormat = getComponentsUtils().getResponseFormat(e); throw e; - } - finally{ - getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo, - request, artifactDefinition, artifactUUID); + } finally { + getComponentsUtils() + .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo, request, artifactDefinition, + artifactUUID); } return responseWrapper.getInnerElement(); } @@ -644,49 +535,32 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @DELETE @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "deletes an artifact of a resource or service", method = "DELETE", - summary = "deletes an artifact of a resource or service", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Artifact deleted", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(responseCode = "400", - description = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), - @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), - @ApiResponse(responseCode = "403", - description = "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(responseCode = "409", - description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @Operation(description = "deletes an artifact of a resource or service", method = "DELETE", summary = "deletes an artifact of a resource or service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Artifact deleted", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), + @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), + @ApiResponse(responseCode = "403", description = "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(responseCode = "409", description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) @PermissionAllowed(AafPermission.PermNames.DELETE_VALUE) public Response deleteArtifact( - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type", - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter( - description = "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) { - + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(schema = @Schema(allowableValues = { + "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "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(); @@ -694,10 +568,8 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { log.debug(DOUBLE_CURLY_BRACKETS, startLog, url); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); String componentTypeValue = componentType == null ? null : componentType.getValue(); - ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue); ArtifactDefinition artifactDefinition = null; - if (componentType == null) { log.debug("deleteArtifact: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -713,11 +585,11 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); } - try { if (responseWrapper.isEmpty()) { - artifactDefinition = artifactsBusinessLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, - resourceCommonInfo, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE)); + artifactDefinition = artifactsBusinessLogic + .deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, resourceCommonInfo, + new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE)); Object representation = RepresentationUtils.toRepresentation(artifactDefinition); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); @@ -730,13 +602,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { log.debug(message, e); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } catch (ComponentException e){ + } catch (ComponentException e) { responseFormat = getComponentsUtils().getResponseFormat(e); throw e; - } - finally{ - getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo, - request, artifactDefinition, artifactUUID); + } finally { + getComponentsUtils() + .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo, request, artifactDefinition, + artifactUUID); } return responseWrapper.getInnerElement(); } @@ -747,51 +619,33 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @DELETE @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "deletes an artifact of a resource insatnce", method = "DELETE", - summary = "deletes an artifact of a resource insatnce", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Artifact deleted", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(responseCode = "400", - description = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), - @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), - @ApiResponse(responseCode = "403", - description = "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(responseCode = "409", - description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @Operation(description = "deletes an artifact of a resource insatnce", method = "DELETE", summary = "deletes an artifact of a resource insatnce", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Artifact deleted", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"), + @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), + @ApiResponse(responseCode = "403", description = "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(responseCode = "409", description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) @PermissionAllowed(AafPermission.PermNames.DELETE_VALUE) public Response deleteArtifactOnResourceInstance( - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type", - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter( - description = "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, - @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", - required = true) @PathParam("resourceInstanceName") final String resourceInstanceName) { - + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(schema = @Schema(allowableValues = { + "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "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, + @Parameter(description = "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(); @@ -800,7 +654,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); String componentTypeValue = componentType == null ? null : componentType.getValue(); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue); - if (componentType == null) { log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); @@ -820,7 +673,7 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { try { if (responseWrapper.isEmpty()) { artifactDefinition = artifactsBusinessLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID, - new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE)); + new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE)); Object representation = RepresentationUtils.toRepresentation(artifactDefinition); Map headers = new HashMap<>(); headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); @@ -833,13 +686,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { log.debug(message, e); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } catch (ComponentException e){ + } catch (ComponentException e) { responseFormat = getComponentsUtils().getResponseFormat(e); throw e; - } - finally{ - getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo, - request, artifactDefinition, artifactUUID); + } finally { + getComponentsUtils() + .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo, request, artifactDefinition, + artifactUUID); } return responseWrapper.getInnerElement(); } @@ -850,40 +703,26 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @GET @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Download component artifact", method = "GET", summary = "Returns downloaded artifact", - responses = {@ApiResponse(responseCode = "200", description = "Artifact downloaded", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "400", - description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "404", description = "Artifact was not found - SVC4505")}) + @Operation(description = "Download component artifact", method = "GET", summary = "Returns downloaded artifact", responses = { + @ApiResponse(responseCode = "200", description = "Artifact downloaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "404", description = "Artifact was not found - SVC4505")}) @PermissionAllowed(AafPermission.PermNames.DELETE_VALUE) public Response downloadComponentArtifact( - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type", - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter( - description = "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) { - + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(schema = @Schema(allowableValues = { + "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "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(); @@ -911,13 +750,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); } - } catch (ComponentException e){ + } catch (ComponentException e) { responseFormat = getComponentsUtils().getResponseFormat(e); throw e; - } - finally{ - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, resourceCommonInfo, - new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId); + } finally { + getComponentsUtils() + .auditExternalDownloadArtifact(responseFormat, resourceCommonInfo, new DistributionData(instanceIdHeader, requestURI), requestId, + artifactUUID, userId); } return responseWrapper.getInnerElement(); } @@ -928,43 +767,27 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @GET @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Download resource instance artifact", method = "GET", - summary = "Returns downloaded artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Artifact downloaded", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "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(responseCode = "404", description = "Artifact was not found - SVC4505")}) + @Operation(description = "Download resource instance artifact", method = "GET", summary = "Returns downloaded artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Artifact downloaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "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(responseCode = "404", description = "Artifact was not found - SVC4505")}) @PermissionAllowed(AafPermission.PermNames.READ_VALUE) public Response downloadResourceInstanceArtifact( - @Parameter(description = "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, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The requested asset type", - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", - required = true) @PathParam("uuid") final String uuid, - @Parameter( - description = "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, - @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", - required = true) @PathParam("resourceInstanceName") final String resourceInstanceName) { - + @Parameter(description = "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, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The requested asset type", required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "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, + @Parameter(description = "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(); @@ -984,20 +807,20 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { } try { if (responseWrapper.isEmpty()) { - byte[] value = artifactsBusinessLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID); + byte[] value = artifactsBusinessLogic + .downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID); 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 (ComponentException e){ + } catch (ComponentException e) { responseFormat = getComponentsUtils().getResponseFormat(e); throw e; - } - finally{ + } finally { getComponentsUtils().auditExternalDownloadArtifact(responseFormat, new ResourceCommonInfo(resourceInstanceName, componentTypeValue), - new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId); + new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId); } 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 0154284cab..1c8f15042a 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 @@ -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. @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet; +import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE; + import com.jcabi.aspects.Loggable; import fj.data.Either; import io.swagger.v3.oas.annotations.Operation; @@ -32,6 +33,24 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.inject.Inject; +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 org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider; @@ -65,34 +84,11 @@ import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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 java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE; - /** * This Servlet serves external users for retrieving component metadata. - * - * @author tgitelman * + * @author tgitelman */ - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Tags({@Tag(name = "SDC External APIs")}) @@ -100,22 +96,20 @@ import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE; @Controller public class AssetsDataServlet extends AbstractValidationsServlet { - @Context - private HttpServletRequest request; - private static final Logger log = Logger.getLogger(AssetsDataServlet.class); - private final ElementBusinessLogic elementBusinessLogic; private final AssetMetadataConverter assetMetadataConverter; private final ServiceBusinessLogic serviceBusinessLogic; private final ResourceBusinessLogic resourceBusinessLogic; private final ComponentBusinessLogicProvider componentBusinessLogicProvider; + @Context + private HttpServletRequest request; @Inject - public AssetsDataServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, - ElementBusinessLogic elementBusinessLogic, AssetMetadataConverter assetMetadataConverter, - ComponentBusinessLogicProvider componentBusinessLogicProvider, ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) { + public AssetsDataServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, + ServletUtils servletUtils, ResourceImportManager resourceImportManager, ElementBusinessLogic elementBusinessLogic, + AssetMetadataConverter assetMetadataConverter, ComponentBusinessLogicProvider componentBusinessLogicProvider, + ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.elementBusinessLogic = elementBusinessLogic; this.assetMetadataConverter = assetMetadataConverter; @@ -128,50 +122,33 @@ public class AssetsDataServlet extends AbstractValidationsServlet { @Path("/{assetType}") @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Fetch list of assets", method = "GET", summary = "Returns list of assets", responses = { - @ApiResponse(responseCode = "200", - description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) @PermissionAllowed(AafPermission.PermNames.READ_VALUE) public Response getAssetListExternal( - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}), - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The filter key (resourceType only for resources)", - required = false) @QueryParam("category") String category, - @Parameter(description = "The filter key (resourceType only for resources)", - required = false) @QueryParam("subCategory") String subCategory, - @Parameter(description = "The filter key (resourceType only for resources)", - required = false) @QueryParam("distributionStatus") String distributionStatus, - @Parameter(description = "The filter key (resourceType only for resources)", - required = false) @QueryParam("resourceType") String resourceType) throws IOException { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources", + "services"}), required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("category") String category, + @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("subCategory") String subCategory, + @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("distributionStatus") String distributionStatus, + @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("resourceType") String resourceType) + throws IOException { ResponseFormat responseFormat = null; String query = request.getQueryString(); - String requestURI = request.getRequestURI().endsWith("/")? - removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI(); + 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; - String resourceUrl = query == null ? requestURI : requestURI + "?" + query; DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl); - // Mandatory if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); @@ -179,10 +156,8 @@ public class AssetsDataServlet extends AbstractValidationsServlet { getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId); return buildErrorResponse(responseFormat); } - try { Map filters = new EnumMap<>(FilterKeyEnum.class); - if (category != null) { filters.put(FilterKeyEnum.CATEGORY, category); } @@ -202,9 +177,8 @@ public class AssetsDataServlet extends AbstractValidationsServlet { } filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name()); } - - Either, ResponseFormat> assetTypeData = elementBusinessLogic.getFilteredCatalogComponents(assetType, filters, query); - + Either, ResponseFormat> assetTypeData = elementBusinessLogic + .getFilteredCatalogComponents(assetType, filters, query); if (assetTypeData.isRight()) { log.debug("getAssetList: Asset Fetching Failed"); responseFormat = assetTypeData.right().value(); @@ -212,7 +186,8 @@ public class AssetsDataServlet extends AbstractValidationsServlet { return buildErrorResponse(responseFormat); } else { log.debug("getAssetList: Asset Fetching Success"); - Either, ResponseFormat> resMetadata = assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false); + Either, ResponseFormat> resMetadata = assetMetadataConverter + .convertToAssetMetadata(assetTypeData.left().value(), requestURI, false); if (resMetadata.isRight()) { log.debug("getAssetList: Asset conversion Failed"); responseFormat = resMetadata.right().value(); @@ -222,7 +197,6 @@ public class AssetsDataServlet extends AbstractValidationsServlet { Object result = RepresentationUtils.toRepresentation(resMetadata.left().value()); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId); - return buildOkResponse(responseFormat, result); } } catch (Exception e) { @@ -233,7 +207,6 @@ public class AssetsDataServlet extends AbstractValidationsServlet { } /** - * * @param requestId * @param instanceIdHeader * @param accept @@ -245,41 +218,28 @@ public class AssetsDataServlet extends AbstractValidationsServlet { @GET @Path("/{assetType}/{uuid}/metadata") @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Detailed metadata of asset by uuid", method = "GET", - summary = "Returns detailed metadata of an asset by uuid", responses = {@ApiResponse(responseCode = "200", - description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", - description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + @Operation(description = "Detailed metadata of asset by uuid", method = "GET", summary = "Returns detailed metadata of an asset by uuid", responses = { + @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) @PermissionAllowed(AafPermission.PermNames.READ_VALUE) public Response getAssetSpecificMetadataByUuidExternal( - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}), - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The requested asset uuid", - required = true) @PathParam("uuid") final String uuid) throws IOException { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources", + "services"}), required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException { 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); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue()); DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI); @@ -287,39 +247,31 @@ public class AssetsDataServlet extends AbstractValidationsServlet { 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, distributionData, - resourceCommonInfo, requestId, uuid); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildErrorResponse(responseFormat); } - try { - - Either, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); - + Either, ResponseFormat> assetTypeData = elementBusinessLogic + .getCatalogComponentsByUuidAndAssetType(assetType, uuid); if (assetTypeData.isRight()) { log.debug("getAssetList: Asset Fetching Failed"); responseFormat = assetTypeData.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); - + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildErrorResponse(responseFormat); } resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName()); log.debug("getAssetList: Asset Fetching Success"); - Either, ResponseFormat> resMetadata = assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true); + Either, ResponseFormat> resMetadata = assetMetadataConverter + .convertToAssetMetadata(assetTypeData.left().value(), requestURI, true); if (resMetadata.isRight()) { log.debug("getAssetList: Asset conversion Failed"); responseFormat = resMetadata.right().value(); - - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildErrorResponse(responseFormat); } Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next()); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); - + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildOkResponse(responseFormat, result); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); @@ -329,7 +281,7 @@ public class AssetsDataServlet extends AbstractValidationsServlet { } private ComponentBusinessLogic getComponentBLByType(ComponentTypeEnum componentTypeEnum) { - if(componentTypeEnum.equals(RESOURCE)) { + if (componentTypeEnum.equals(RESOURCE)) { return resourceBusinessLogic; } else { // Implementation is the same for any ComponentBusinessLogic @@ -338,7 +290,6 @@ public class AssetsDataServlet extends AbstractValidationsServlet { } /** - * * @param requestId * @param instanceIdHeader * @param accept @@ -347,57 +298,40 @@ public class AssetsDataServlet extends AbstractValidationsServlet { * @param uuid * @return */ - @GET @Path("/{assetType}/{uuid}/toscaModel") @Produces(MediaType.APPLICATION_OCTET_STREAM) @Operation(description = "Fetch assets CSAR", method = "GET", summary = "Returns asset csar", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", - description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", - description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) @PermissionAllowed(AafPermission.PermNames.READ_VALUE) public Response getToscaModelExternal( - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}), - required = true) @PathParam("assetType") final String assetType, - @Parameter(description = "The requested asset uuid", - required = true) @PathParam("uuid") final String uuid) { - + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources", + "services"}), required = true) @PathParam("assetType") final String assetType, + @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) { String url = request.getRequestURI(); log.debug("Start handle request of {} {}", request.getMethod(), url); ResponseFormat responseFormat = null; ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL; - ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue()); DistributionData distributionData = new DistributionData(instanceIdHeader, url); - 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, distributionData, - resourceCommonInfo, requestId, uuid); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildErrorResponse(responseFormat); } - try { ComponentBusinessLogic componentBusinessLogic = getComponentBLByType(componentType); ImmutablePair csarArtifact = componentBusinessLogic.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo); @@ -408,25 +342,20 @@ public class AssetsDataServlet extends AbstractValidationsServlet { headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.getLeft())); headers.put(Constants.MD5_HEADER, contenetMD5); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return buildOkResponse(responseFormat, is, headers); - } catch (ComponentException e) { responseFormat = e.getResponseFormat(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model"); log.debug("failed to get asset tosca model", e); Response response = buildErrorResponse(responseFormat); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, uuid); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid); return response; } } - private String removeDuplicateSlashSeparator(String requestUri) { - return requestUri.substring(0, requestUri.length()-1); + 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 97678d72fc..5f6d8eaeda 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet; import static com.google.common.base.Strings.isNullOrEmpty; @@ -104,26 +103,21 @@ import org.springframework.stereotype.Controller; @Controller public class CrudExternalServlet extends AbstractValidationsServlet { - @Context - private HttpServletRequest request; - private static final Logger log = Logger.getLogger(CrudExternalServlet.class); private final ElementBusinessLogic elementBusinessLogic; private final AssetMetadataConverter assetMetadataUtils; private final LifecycleBusinessLogic lifecycleBusinessLogic; private final ResourceBusinessLogic resourceBusinessLogic; private final ServiceBusinessLogic serviceBusinessLogic; + @Context + private HttpServletRequest request; @Inject - public CrudExternalServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - ElementBusinessLogic elementBusinessLogic, - AssetMetadataConverter assetMetadataUtils, - LifecycleBusinessLogic lifecycleBusinessLogic, - ResourceBusinessLogic resourceBusinessLogic, - ServiceBusinessLogic serviceBusinessLogic) { + public CrudExternalServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, + ElementBusinessLogic elementBusinessLogic, AssetMetadataConverter assetMetadataUtils, + LifecycleBusinessLogic lifecycleBusinessLogic, ResourceBusinessLogic resourceBusinessLogic, + ServiceBusinessLogic serviceBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.elementBusinessLogic = elementBusinessLogic; this.assetMetadataUtils = assetMetadataUtils; @@ -146,74 +140,41 @@ public class CrudExternalServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(parameters = { - @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.Resource.class), - description = "json describe the created resource")}, - description = "creates an asset (resource or service)", method = "POST", - summary = "Creates an asset (resource or service)", responses = { - @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and Asset created", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", - description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(responseCode = "400", - description = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"), - @ApiResponse(responseCode = "400", - description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), - @ApiResponse(responseCode = "400", - description = "Missing request body. The post request did not contain the expected body - SVC4500"), - @ApiResponse(responseCode = "400", - description = "The resource name is missing in the request body - SVC4062"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT description has wrong format - SVC4064"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT name has wrong format - SVC4070"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"), - @ApiResponse(responseCode = "400", - description = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073"), - @ApiResponse(responseCode = "400", description = "Invalid Content. Missing PROJECT_CODE number - SVC4129"), - @ApiResponse(responseCode = "409", - description = "Error: %1 (Service) with name '%2' already exists. - SVC4050")}) + @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.Resource.class), description = "json describe the created resource")}, description = "creates an asset (resource or service)", method = "POST", summary = "Creates an asset (resource or service)", responses = { + @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and Asset created", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(responseCode = "400", description = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"), + @ApiResponse(responseCode = "400", description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), + @ApiResponse(responseCode = "400", description = "Missing request body. The post request did not contain the expected body - SVC4500"), + @ApiResponse(responseCode = "400", description = "The resource name is missing in the request body - SVC4062"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT description has wrong format - SVC4064"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT name has wrong format - SVC4070"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"), + @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073"), + @ApiResponse(responseCode = "400", description = "Invalid Content. Missing PROJECT_CODE number - SVC4129"), + @ApiResponse(responseCode = "409", description = "Error: %1 (Service) with name '%2' already exists. - SVC4050")}) @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE) public Response createComponentExternal( - @Parameter(description = "Determines the format of the body of the request", - required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "The user id", - required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The requested asset type", required = true, - schema = @Schema( - allowableValues = {"resources, services"})) @PathParam("assetType") final String assetType, - @Parameter(hidden = true) String data) { - + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The requested asset type", required = true, schema = @Schema(allowableValues = { + "resources, services"})) @PathParam("assetType") final String assetType, @Parameter(hidden = true) String data) { init(); - Wrapper responseWrapper = new Wrapper<>(); String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; @@ -222,7 +183,6 @@ public class CrudExternalServlet extends AbstractValidationsServlet { User modifier = null; ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(ComponentTypeEnum.RESOURCE.getValue()); Service service = null; - try { // Validate X-ECOMP-InstanceID Header if (responseWrapper.isEmpty()) { @@ -233,75 +193,62 @@ public class CrudExternalServlet extends AbstractValidationsServlet { validateHttpCspUserIdHeader(userId, responseWrapper); } // Validate assetType - - if( responseWrapper.isEmpty() && !(AssetTypeEnum.RESOURCES.getValue().equals(assetType) || AssetTypeEnum.SERVICES.getValue().equals(assetType))) { + if (responseWrapper.isEmpty() && !(AssetTypeEnum.RESOURCES.getValue().equals(assetType) || AssetTypeEnum.SERVICES.getValue() + .equals(assetType))) { responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } - - if (responseWrapper.isEmpty() && AssetTypeEnum.SERVICES.getValue().equals(assetType)) { - + if (responseWrapper.isEmpty() && AssetTypeEnum.SERVICES.getValue().equals(assetType)) { modifier = new User(); modifier.setUserId(userId); Either convertResponse = getComponentsUtils() - .convertJsonToObjectUsingObjectMapper(data, modifier, Service.class, - null, ComponentTypeEnum.SERVICE); - if( convertResponse.isRight() ){ + .convertJsonToObjectUsingObjectMapper(data, modifier, Service.class, null, ComponentTypeEnum.SERVICE); + if (convertResponse.isRight()) { responseWrapper.setInnerElement(convertResponse.right().value()); - } - else{ + } else { service = convertResponse.left().value(); } - - if (service==null){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.SERVICE_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue())); + if (service == null) { + responseWrapper.setInnerElement( + getComponentsUtils().getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue())); } - //validate name exist - if(responseWrapper.isEmpty() && service != null && isNullOrEmpty(service.getName())){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue())); + if (responseWrapper.isEmpty() && service != null && isNullOrEmpty(service.getName())) { + responseWrapper.setInnerElement( + getComponentsUtils().getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue())); } - //validate category - if(responseWrapper.isEmpty() && service != null && service.getCategories() != null && !service.getCategories().isEmpty() && !ExternalCategoryTypeEnum.containsIgnoreCase(service.getCategories().get(0).getName())){ + if (responseWrapper.isEmpty() && service != null && service.getCategories() != null && !service.getCategories().isEmpty() + && !ExternalCategoryTypeEnum.containsIgnoreCase(service.getCategories().get(0).getName())) { log.debug("Service category is not supported {}", service.getCategories().get(0).getName()); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue())); + responseWrapper.setInnerElement( + getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue())); } - - if(responseWrapper.isEmpty() && service != null){ + if (responseWrapper.isEmpty() && service != null) { service.setSystemName(ValidationUtils.convertToSystemName(service.getName())); - log.debug("Service system name :"+service.getSystemName()); + log.debug("Service system name :" + service.getSystemName()); } - - if(responseWrapper.isEmpty()){ - Either actionResponse = serviceBusinessLogic.createService(service, modifier); + if (responseWrapper.isEmpty()) { + Either actionResponse = serviceBusinessLogic.createService(service, modifier); if (actionResponse.isRight()) { log.debug("Failed to create service"); - responseWrapper.setInnerElement(actionResponse.right().value()); - return buildErrorResponse(responseWrapper.getInnerElement()); + responseWrapper.setInnerElement(actionResponse.right().value()); + return buildErrorResponse(responseWrapper.getInnerElement()); } - // Create the service in the dataModel service = actionResponse.left().value(); Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED)); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); - } - else{ - return buildErrorResponse(responseWrapper.getInnerElement()); + } else { + return buildErrorResponse(responseWrapper.getInnerElement()); } - - - - } else { + } else { //Validate resource type - if(responseWrapper.isEmpty()){ + 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) ){ + if (StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType)) { resourceCommonInfo.setResourceName((String) jsonObj.get("name")); responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } @@ -311,64 +258,57 @@ public class CrudExternalServlet extends AbstractValidationsServlet { modifier = new User(); modifier.setUserId(userId); Either eitherResource = getComponentsUtils() - .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, - null, ComponentTypeEnum.RESOURCE); - if( eitherResource.isRight() ){ + .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, null, ComponentTypeEnum.RESOURCE); + if (eitherResource.isRight()) { responseWrapper.setInnerElement(eitherResource.right().value()); - } - else{ + } else { resource = eitherResource.left().value(); } - } //validate name exist - if(responseWrapper.isEmpty() && isNullOrEmpty(resource.getName())){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue())); + if (responseWrapper.isEmpty() && isNullOrEmpty(resource.getName())) { + responseWrapper.setInnerElement( + getComponentsUtils().getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue())); } - - if(responseWrapper.isEmpty()){ + 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())); + resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(), resource.getSystemName())); handleCategories(data, resource, responseWrapper); } // Create the resource in the dataModel if (responseWrapper.isEmpty()) { - resource = resourceBusinessLogic.createResource(resource, null, - modifier, null, null); + resource = resourceBusinessLogic.createResource(resource, null, modifier, null, null); return buildCreatedResourceResponse(resource, responseWrapper); } else { return buildErrorResponse(responseWrapper.getInnerElement()); } } - - } catch (IOException|ParseException e) { + } catch (IOException | ParseException e) { final String message = "failed to create vfc monitoring template resource"; BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); log.debug(message, e); responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); return buildErrorResponse(responseWrapper.getInnerElement()); - } catch (ComponentException e){ + } catch (ComponentException e) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(e); responseWrapper.setInnerElement(responseFormat); return buildErrorResponse(responseFormat); - } - finally { - if(AssetTypeEnum.RESOURCES.getValue().equals(assetType)) { - getComponentsUtils().auditCreateResourceExternalApi(responseWrapper.getInnerElement(), resourceCommonInfo, request, resource); - } else if(AssetTypeEnum.SERVICES.getValue().equals(assetType)) { - getComponentsUtils().auditCreateServiceExternalApi(responseWrapper.getInnerElement(), request, service); - } + } finally { + if (AssetTypeEnum.RESOURCES.getValue().equals(assetType)) { + getComponentsUtils().auditCreateResourceExternalApi(responseWrapper.getInnerElement(), resourceCommonInfo, request, resource); + } else if (AssetTypeEnum.SERVICES.getValue().equals(assetType)) { + getComponentsUtils().auditCreateServiceExternalApi(responseWrapper.getInnerElement(), request, service); + } } } /** * 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 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 @@ -378,67 +318,45 @@ public class CrudExternalServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(parameters = { - @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.Resource.class), - description = "json describe the created resource")}, - description = "Change Resource lifecycle State", method = "POST", responses = { - @ApiResponse(responseCode = "200", description = "Resource state changed", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))), - @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", - description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(responseCode = "403", description = "Asset is already checked-out by another user - SVC4085"), - @ApiResponse(responseCode = "403", - description = "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")}) + @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.Resource.class), description = "json describe the created resource")}, description = "Change Resource lifecycle State", method = "POST", responses = { + @ApiResponse(responseCode = "200", description = "Resource state changed", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))), + @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(responseCode = "403", description = "Asset is already checked-out by another user - SVC4085"), + @ApiResponse(responseCode = "403", description = "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")}) @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE) public Response changeResourceStateExternal( - @Parameter(description = "Determines the format of the body of the request", - required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "The user id", - required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(schema = @Schema(allowableValues = {"checkout, checkin"}), - required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, - @Parameter(description = "id of component to be changed") @PathParam(value = "uuid") final String uuid, - @Parameter(description = "validValues: resources / services ", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME , - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam( - value = "assetType") final String assetType, - @Parameter(hidden = true) String jsonChangeInfo) { - + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(schema = @Schema(allowableValues = { + "checkout, checkin"}), required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, + @Parameter(description = "id of component to be changed") @PathParam(value = "uuid") final String uuid, + @Parameter(description = "validValues: resources / services ", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam(value = "assetType") final String assetType, + @Parameter(hidden = true) String jsonChangeInfo) { Response response = null; - init(); - String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; log.debug("Start handle request of {}", url); - Wrapper responseWrapper = runValidations(assetType); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); Component component = null; Component responseObject = null; User modifier = null; - - try{ + try { // Validate X-ECOMP-InstanceID Header if (responseWrapper.isEmpty()) { validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); } - if (responseWrapper.isEmpty()) { //get user Either eitherGetUser = getUser(request, userId); @@ -448,7 +366,6 @@ public class CrudExternalServlet extends AbstractValidationsServlet { return buildErrorResponse(responseFormat); } modifier = eitherGetUser.left().value(); - //get the component id from the uuid Either latestVersion = lifecycleBusinessLogic.getLatestComponentByUuid(componentType, uuid); if (latestVersion.isRight()) { @@ -458,7 +375,6 @@ public class CrudExternalServlet extends AbstractValidationsServlet { } component = latestVersion.left().value(); String componentId = component.getUniqueId(); - //validate the transition is valid Either validateEnum = validateTransitionEnum(lifecycleTransition, modifier); if (validateEnum.isRight()) { @@ -467,39 +383,37 @@ public class CrudExternalServlet extends AbstractValidationsServlet { 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()); + changeInfo = new LifecycleChangeInfoWithAction( + mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); } - } - catch (IOException e) { + } catch (IOException e) { BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); log.debug("failed to convert from json {}", jsonChangeInfo, e); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + ResponseFormat responseFormat = getComponentsUtils() + .getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); responseWrapper.setInnerElement(responseFormat); return buildErrorResponse(responseFormat); } - //execute business logic - Either actionResponse = lifecycleBusinessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true); + Either actionResponse = lifecycleBusinessLogic + .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, responseWrapper); } else { response = buildErrorResponse(responseWrapper.getInnerElement()); } - return response; } catch (IOException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); @@ -507,33 +421,29 @@ public class CrudExternalServlet extends AbstractValidationsServlet { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); responseWrapper.setInnerElement(responseFormat); return buildErrorResponse(responseFormat); - } catch (ComponentException e){ + } catch (ComponentException e) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(e); responseWrapper.setInnerElement(responseFormat); return buildErrorResponse(responseFormat); - } - finally{ - getComponentsUtils().auditChangeLifecycleAction(responseWrapper.getInnerElement(), componentType, requestId, - component, responseObject, new DistributionData(instanceIdHeader, requestURI), modifier); + } finally { + getComponentsUtils().auditChangeLifecycleAction(responseWrapper.getInnerElement(), componentType, requestId, component, responseObject, + new DistributionData(instanceIdHeader, requestURI), modifier); } } - private Response buildCreatedResourceResponse(Component resource, - Wrapper responseWrapper) throws IOException { + private Response buildCreatedResourceResponse(Component resource, Wrapper responseWrapper) throws IOException { ResponseFormat responseFormat; Response response; Either resMetadata = assetMetadataUtils - .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(), - true); + .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{ + } 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); @@ -541,29 +451,24 @@ public class CrudExternalServlet extends AbstractValidationsServlet { return response; } - private void handleCategories(String data, Resource resource, - Wrapper responseWrapper) { + private void handleCategories(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 (isNullOrEmpty(category)) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - else if (isNullOrEmpty(subcategory)) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_MISSING_SUBCATEGORY)); + responseWrapper.setInnerElement( + getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } else if (isNullOrEmpty(subcategory)) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY)); } if (responseWrapper.isEmpty()) { // get All Categories - Either, ActionStatus> allResourceCategories = elementBusinessLogic - .getAllResourceCategories(); + Either, ActionStatus> allResourceCategories = elementBusinessLogic.getAllResourceCategories(); // Error fetching categories if (allResourceCategories.isRight()) { - responseWrapper.setInnerElement( - getComponentsUtils().getResponseFormat(allResourceCategories.right().value())); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(allResourceCategories.right().value())); } else { addCategories(resource, category, subcategory, allResourceCategories, responseWrapper); } @@ -572,65 +477,57 @@ public class CrudExternalServlet extends AbstractValidationsServlet { 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) { + 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(); + // 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())); + 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{ + // 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 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); + validateXECOMPInstanceIDHeader(instanceId, responseWrapper); } // Validate USER_ID Header if (responseWrapper.isEmpty()) { - validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper); + validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER), responseWrapper); } // Validate assetType - if (responseWrapper.isEmpty() - && !AssetTypeEnum.RESOURCES.getValue().equals(assetType) - && !AssetTypeEnum.SERVICES.getValue().equals(assetType)) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + if (responseWrapper.isEmpty() && !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue() + .equals(assetType)) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } - return responseWrapper; } @@ -643,5 +540,4 @@ public class CrudExternalServlet extends AbstractValidationsServlet { return Either.right(error); } } - } 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 index 121460c1f5..f93e99eecd 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet; import fj.data.Either; @@ -25,19 +24,8 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic; -import org.openecomp.sdc.be.components.impl.aaf.AafPermission; -import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.dto.ExternalRefDTO; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.servlets.BeGenericServlet; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.datastructure.Wrapper; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Controller; - +import java.util.List; +import java.util.Map; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -51,8 +39,18 @@ import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.List; -import java.util.Map; +import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic; +import org.openecomp.sdc.be.components.impl.aaf.AafPermission; +import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.dto.ExternalRefDTO; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.servlets.BeGenericServlet; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Controller; @Path("/v1/catalog") @Tags({@Tag(name = "SDC External APIs")}) @@ -64,9 +62,8 @@ public class ExternalRefsServlet extends BeGenericServlet { private final ExternalRefsBusinessLogic businessLogic; @Inject - public ExternalRefsServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - ExternalRefsBusinessLogic externalRefsBusinessLogic) { + public ExternalRefsServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + ExternalRefsBusinessLogic externalRefsBusinessLogic) { super(userBusinessLogic, componentsUtils); this.businessLogic = externalRefsBusinessLogic; } @@ -75,22 +72,18 @@ public class ExternalRefsServlet extends BeGenericServlet { @Path("/{assetType}/{uuid}/version/{version}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}") @Produces(MediaType.APPLICATION_JSON) @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) - public Response getComponentInstanceExternalRef( - @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, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { - + public Response getComponentInstanceExternalRef(@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, + @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { log.debug("GET component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); - Response r = validateRequest(xEcompInstanceId); - if (r != null){ + if (r != null) { return r; } - Either, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, componentInstanceName, objectType); - if (refsResult.isLeft()){ + if (refsResult.isLeft()) { return this.buildOkResponse(refsResult.left().value()); } else { return this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, componentInstanceName, objectType, ""); @@ -101,21 +94,17 @@ public class ExternalRefsServlet extends BeGenericServlet { @Path("/{assetType}/{uuid}/version/{version}/externalReferences/{objectType}") @Produces(MediaType.APPLICATION_JSON) @PermissionAllowed({AafPermission.PermNames.READ_VALUE}) - public Map> getAssetExternalRefByObjectType( - @PathParam("assetType") String assetType, - @PathParam("uuid") String uuid, - @PathParam("version") String version, - @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { - + public Map> getAssetExternalRefByObjectType(@PathParam("assetType") String assetType, @PathParam("uuid") String uuid, + @PathParam("version") String version, @PathParam("objectType") String objectType, + @HeaderParam("USER_ID") String userId, + @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { log.debug("GET asset external references {} {} {}", assetType, uuid, objectType); - Response r = validateRequest(xEcompInstanceId); - if (r != null){ + if (r != null) { throw new WebApplicationException(r); } - Either>, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, objectType); - if (refsResult.isLeft()){ + if (refsResult.isLeft()) { return refsResult.left().value(); } else { throw new WebApplicationException(this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, "", objectType, "")); @@ -127,53 +116,46 @@ public class ExternalRefsServlet extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @PermissionAllowed({AafPermission.PermNames.WRITE_VALUE}) - public Response addComponentInstanceExternalRef( - @PathParam("assetType") String assetType, - @PathParam("uuid") String uuid, - @PathParam("componentInstanceName") String componentInstanceName, - @PathParam("objectType") String objectType, ExternalRefDTO ref, @HeaderParam("USER_ID") String userId, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { - + public Response addComponentInstanceExternalRef(@PathParam("assetType") String assetType, @PathParam("uuid") String uuid, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, ExternalRefDTO ref, + @HeaderParam("USER_ID") String userId, + @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { log.debug("POST component instance external interfaces {} {} {} {} {}", assetType, uuid, componentInstanceName, objectType, ref); - Response r = validateRequest(xEcompInstanceId); - if (r != null){ + if (r != null) { return r; } - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); String uid = this.businessLogic.fetchComponentUniqueIdByUuid(uuid, componentType); - Either addResult = this.businessLogic.addExternalReference(uid, componentType, userId, componentInstanceName, objectType, ref); + Either addResult = this.businessLogic + .addExternalReference(uid, componentType, userId, componentInstanceName, objectType, ref); if (addResult.isLeft()) { - return Response.status(Response.Status.CREATED) - .entity(ref) - .build(); + 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) @PermissionAllowed({AafPermission.PermNames.DELETE_VALUE}) - public Response deleteComponentInstanceReference( - @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, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { - + public Response deleteComponentInstanceReference(@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, + @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { log.debug("DELETE component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); - Response r = validateRequest(xEcompInstanceId); - if (r != null){ + if (r != null) { return r; } ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); String uid = this.businessLogic.fetchComponentUniqueIdByUuid(uuid, componentType); - Either deleteStatus = this.businessLogic.deleteExternalReference(uid, componentType, userId, componentInstanceName, objectType, reference); - if (deleteStatus.isLeft()){ + Either deleteStatus = this.businessLogic + .deleteExternalReference(uid, componentType, userId, componentInstanceName, objectType, reference); + if (deleteStatus.isLeft()) { return this.buildOkResponse(new ExternalRefDTO(reference)); } else { return this.buildExtRefErrorResponse(deleteStatus.right().value(), uuid, "", componentInstanceName, objectType, reference); @@ -185,45 +167,39 @@ public class ExternalRefsServlet extends BeGenericServlet { @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @PermissionAllowed({AafPermission.PermNames.WRITE_VALUE}) - public Response updateComponentInstanceReference( - @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, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { - + public Response updateComponentInstanceReference(@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, + @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) { log.debug("PUT component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); - Response r = validateRequest(xEcompInstanceId); - if (r != null){ + if (r != null) { return r; } - String newRefValue = newRefValueDTO.getReferenceUUID(); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); String uid = this.businessLogic.fetchComponentUniqueIdByUuid(uuid, componentType); - Either updateResult = this.businessLogic.updateExternalReference(uid, componentType, userId, componentInstanceName, objectType, oldRefValue, newRefValue); - if (updateResult.isLeft()){ + Either updateResult = this.businessLogic + .updateExternalReference(uid, componentType, userId, 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 validateRequest(String xEcompInstanceIdHeader) { Wrapper responseWrapper = new Wrapper<>(); - //Validate X-ECOMP_INSTANCE_ID_HEADER - if (xEcompInstanceIdHeader == null || xEcompInstanceIdHeader.isEmpty()){ + if (xEcompInstanceIdHeader == null || xEcompInstanceIdHeader.isEmpty()) { return this.buildExtRefErrorResponse(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID, "", "", "", "", ""); } - return responseWrapper.getInnerElement(); } - private Response buildExtRefErrorResponse(ActionStatus status, String uuid, String version, String componentInstanceName, String objectType, String ref){ + 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)); @@ -232,9 +208,7 @@ public class ExternalRefsServlet extends BeGenericServlet { 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(); + 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: 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 index f590ebd96f..d203415ae5 100644 --- 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet; import com.fasterxml.jackson.databind.ObjectMapper; @@ -74,19 +73,15 @@ import org.springframework.stereotype.Controller; @Controller public class ServiceActivationServlet extends AbstractValidationsServlet { - @Context - private HttpServletRequest request; - private static final Logger log = Logger.getLogger(ServiceActivationServlet.class); - private final ServiceBusinessLogic serviceBusinessLogic; + @Context + private HttpServletRequest request; @Inject - public ServiceActivationServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - ServiceBusinessLogic serviceBusinessLogic) { + public ServiceActivationServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, + ServiceBusinessLogic serviceBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.serviceBusinessLogic = serviceBusinessLogic; } @@ -99,67 +94,43 @@ public class ServiceActivationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "activate a service", method = "POST", summary = "Activates a service", responses = { - @ApiResponse(responseCode = "202", - description = "ECOMP component is authenticated and required service may be distributed"), - @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", - description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(responseCode = "400", - description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), - @ApiResponse(responseCode = "400", - description = "Missing request body. The post request did not contain the expected body - SVC4500"), - @ApiResponse(responseCode = "400", - description = "The resource name is missing in the request body - SVC4062"), - @ApiResponse(responseCode = "409", description = "Service state is invalid for this action"), - @ApiResponse(responseCode = "502", - description = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")}) + @ApiResponse(responseCode = "202", description = "ECOMP component is authenticated and required service may be distributed"), + @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(responseCode = "400", description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), + @ApiResponse(responseCode = "400", description = "Missing request body. The post request did not contain the expected body - SVC4500"), + @ApiResponse(responseCode = "400", description = "The resource name is missing in the request body - SVC4062"), + @ApiResponse(responseCode = "409", description = "Service state is invalid for this action"), + @ApiResponse(responseCode = "502", description = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")}) @PermissionAllowed({AafPermission.PermNames.WRITE_VALUE}) public Response activateServiceExternal( - @Parameter(description = "Determines the format of the body of the request", - required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, - @Parameter(description = "The user id", - required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Parameter(description = "The serviceUUid to activate", - required = true) @PathParam("serviceUUID") final String serviceUUID, - @Parameter(description = "The operational environment on which to activate the service on", - required = true) @PathParam("opEnvId") final String opEnvId, - String data) throws IOException { - + @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType, + @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Parameter(description = "The serviceUUid to activate", required = true) @PathParam("serviceUUID") final String serviceUUID, + @Parameter(description = "The operational environment on which to activate the service on", required = true) @PathParam("opEnvId") final String opEnvId, + String data) throws IOException { init(); - ResponseFormat responseFormat = null; String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; log.debug("Start handle request of {}", url); - User modifier = new User(); - try { - Wrapper responseWrapper = validateRequestHeaders(instanceIdHeader, userId); - if (responseWrapper.isEmpty()) { modifier.setUserId(userId); log.debug("modifier id is {}", userId); - ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data); - Either distResponse = serviceBusinessLogic.activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata); - + Either distResponse = serviceBusinessLogic + .activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata); if (distResponse.isRight()) { log.debug("failed to activate service distribution"); responseFormat = distResponse.right().value(); @@ -179,8 +150,8 @@ public class ServiceActivationServlet extends AbstractValidationsServlet { log.debug("activate distribution failed with exception", e); throw e; } finally { - getComponentsUtils().auditExternalActivateService(responseFormat, - new DistributionData(instanceIdHeader, requestURI), requestId, serviceUUID, modifier); + getComponentsUtils() + .auditExternalActivateService(responseFormat, new DistributionData(instanceIdHeader, requestURI), requestId, serviceUUID, modifier); } } @@ -208,13 +179,10 @@ public class ServiceActivationServlet extends AbstractValidationsServlet { @Override protected void validateHttpCspUserIdHeader(String header, Wrapper responseWrapper) { ResponseFormat responseFormat; - if( StringUtils.isEmpty(header)){ + 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/AbstractResourceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AbstractResourceInfo.java index 6bb8356fa4..834eb5f1a3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AbstractResourceInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AbstractResourceInfo.java @@ -15,12 +15,11 @@ */ package org.openecomp.sdc.be.externalapi.servlet.representation; +import java.util.List; import lombok.Getter; import lombok.Setter; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import java.util.List; - @Getter @Setter public class AbstractResourceInfo { @@ -30,6 +29,7 @@ public class AbstractResourceInfo { //获得abstractResourceUniqueId private String abstractResourceUniqueId; //private String abstractResourceNormalizedName; + //获得componentInstancesRelations private List componentInstancesRelations; } 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 7b68ffeee7..5f2a811509 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import lombok.Getter; @@ -26,6 +25,7 @@ import lombok.Setter; @Getter @Setter public class ArtifactMetadata { + private String artifactName; private String artifactType; private String artifactURL; 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 b12411a7b3..67533ca656 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 @@ -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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; public abstract class AssetMetadata implements IAssetMetadata { + private String uuid; private String invariantUUID; private String name; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/CopyServiceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/CopyServiceInfo.java index 078d282aae..f30b2d09d9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/CopyServiceInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/CopyServiceInfo.java @@ -21,9 +21,8 @@ import lombok.Setter; @Getter @Setter public class CopyServiceInfo { - private String newServiceUUid; + private String newServiceUUid; private String newServiceName; - private String oldServiceUUid; } 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 319e16a294..b3a7552b1a 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; public interface IAssetMetadata { @@ -41,5 +40,4 @@ public interface IAssetMetadata { String getToscaModelURL(); 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 90801afa4a..536230a694 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; @@ -27,6 +26,7 @@ import lombok.Setter; @Getter @Setter public class ProductAssetMetadata extends AssetMetadata { + private String lifecycleState; private String lastUpdaterUserId; private boolean active; 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 28137063e2..6af527e613 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import lombok.AllArgsConstructor; @@ -28,6 +27,7 @@ import lombok.Setter; @Setter @AllArgsConstructor public class ProductCategoryGroupMetadata { + private String category; private String subCategory; private String group; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ReplaceVNFInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ReplaceVNFInfo.java index db312e50ad..11c6b609a1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ReplaceVNFInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ReplaceVNFInfo.java @@ -18,24 +18,19 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; import lombok.Getter; import lombok.Setter; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; - -import java.util.List; @Getter @Setter public class ReplaceVNFInfo { + /* delete vnf param */ private String serviceUniqueId; - private String abstractResourceUniqueId; - /* add vnf param */ private ComponentInstance realVNFComponentInstance; - //private List componentInstancesRelations; -} +} 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 0e50c4dafa..a8100454b5 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; 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 a75335aaa1..80e2ec1e43 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import lombok.Getter; @@ -26,6 +25,7 @@ import lombok.Setter; @Getter @Setter public class ResourceAssetMetadata extends AssetMetadata { + private String category; private String subCategory; private String resourceType; 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 da2a9ec466..a219e331fa 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; @@ -27,6 +26,7 @@ import lombok.Setter; @Getter @Setter public class ResourceInstanceMetadata { + private String resourceInstanceName; private String resourceName; private String resourceInvariantUUID; 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 cc4e39878a..1610eceeca 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; @@ -27,6 +26,7 @@ import lombok.Setter; @Getter @Setter public class ServiceAssetDetailedMetadata extends ServiceAssetMetadata { + private String lastUpdaterFullName; private List resources; private List 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 3308343d94..ee3978c961 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import lombok.Getter; @@ -26,6 +25,7 @@ import lombok.Setter; @Getter @Setter public class ServiceAssetMetadata extends AssetMetadata { + private String category; private String lifecycleState; private String lastUpdaterUserId; 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 index 04502510cd..3abc62147c 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; /** @@ -29,6 +28,7 @@ public class ServiceDistributionReqInfo { public ServiceDistributionReqInfo() { } + public ServiceDistributionReqInfo(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 index 1ba33ad257..725fd3cc12 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.externalapi.servlet.representation; import lombok.AllArgsConstructor; @@ -33,5 +32,6 @@ import lombok.Setter; @NoArgsConstructor @AllArgsConstructor public class ServiceDistributionRespInfo { + private String distributionId; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/CatalogOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/CatalogOperation.java index 7836fcce75..8e2111c21b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/CatalogOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/CatalogOperation.java @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.facade.operations; +import java.util.Arrays; +import java.util.List; import org.openecomp.sdc.be.catalog.api.IComponentMessage; import org.openecomp.sdc.be.catalog.api.IStatus; import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum; @@ -33,51 +34,42 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.Arrays; -import java.util.List; - - @org.springframework.stereotype.Component public class CatalogOperation { - - private static final Logger log = Logger.getLogger(CatalogOperation.class); - + + private static final Logger log = Logger.getLogger(CatalogOperation.class); private static final List EXCLUDE_TYPES = Arrays.asList(ResourceTypeEnum.VFCMT, ResourceTypeEnum.Configuration); - private final DmaapProducer msProducer; - - public CatalogOperation(DmaapProducer msProducer){ + + public CatalogOperation(DmaapProducer msProducer) { this.msProducer = msProducer; } - - public ActionStatus updateCatalog(ChangeTypeEnum changeTypeEnum, Component component){ + + public ActionStatus updateCatalog(ChangeTypeEnum changeTypeEnum, Component component) { ActionStatus result = ActionStatus.OK; - try{ - if(isNeedToUpdateCatalog(component)){ - IComponentMessage message = new ComponentMessage(component, changeTypeEnum, CatalogUpdateTimestamp.buildDummyCatalogUpdateTimestamp()); + try { + if (isNeedToUpdateCatalog(component)) { + IComponentMessage message = new ComponentMessage(component, changeTypeEnum, + CatalogUpdateTimestamp.buildDummyCatalogUpdateTimestamp()); IStatus status = msProducer.pushMessage(message); result = FacadeOperationUtils.convertStatusToActionStatus(status); } - - }catch(Exception e){ - log.debug("updateCatalog - failed to updateCatalog and send notification {}", e.getMessage()); - return ActionStatus.OK; - } + } catch (Exception e) { + log.debug("updateCatalog - failed to updateCatalog and send notification {}", e.getMessage()); + return ActionStatus.OK; + } return result; } - - private boolean isNeedToUpdateCatalog(Component component) { - boolean isUpdateCatalog = true; - if(component.getComponentType() == ComponentTypeEnum.RESOURCE){ - return ((Resource)component).isAbstract() || EXCLUDE_TYPES.contains(((Resource)component).getResourceType())? false : true; - - } - return isUpdateCatalog; - } + private boolean isNeedToUpdateCatalog(Component component) { + boolean isUpdateCatalog = true; + if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { + return ((Resource) component).isAbstract() || EXCLUDE_TYPES.contains(((Resource) component).getResourceType()) ? false : true; + } + return isUpdateCatalog; + } public DmaapProducer getMsProducer() { return msProducer; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/FacadeOperationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/FacadeOperationUtils.java index 0cc4a1ccf6..aab98ed49b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/FacadeOperationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/FacadeOperationUtils.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.facade.operations; import org.openecomp.sdc.be.catalog.api.IStatus; @@ -26,14 +25,15 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.common.log.wrappers.Logger; public class FacadeOperationUtils { - private static final Logger log = Logger.getLogger(CatalogOperation.class); - + + private static final Logger log = Logger.getLogger(CatalogOperation.class); + private FacadeOperationUtils() { } public static ActionStatus convertStatusToActionStatus(IStatus status) { ActionStatus result = ActionStatus.OK; - if (status.getResultStatus() != ResultStatusEnum.SUCCESS){ + if (status.getResultStatus() != ResultStatusEnum.SUCCESS) { log.debug("updateCatalog - failed to send notification {}", status); } return result; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/UserOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/UserOperation.java index fb30826bb5..4f444c6086 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/UserOperation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/UserOperation.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.facade.operations; import org.openecomp.sdc.be.catalog.api.IStatus; @@ -31,29 +30,27 @@ import org.springframework.stereotype.Component; @Component public class UserOperation { + private static final Logger log = Logger.getLogger(UserOperation.class); - private final DmaapProducer msProducer; - + private final DmaapProducer msProducer; + @Autowired - public UserOperation(DmaapProducer msProducer){ + public UserOperation(DmaapProducer msProducer) { this.msProducer = msProducer; } - - public ActionStatus updateUserCache(UserOperationEnum operation, String userId, String role){ - try { - UserMessage message = new UserMessage(operation, userId,role); + + public ActionStatus updateUserCache(UserOperationEnum operation, String userId, String role) { + try { + UserMessage message = new UserMessage(operation, userId, role); IStatus status = msProducer.pushMessage(message); return FacadeOperationUtils.convertStatusToActionStatus(status); - - } catch(Exception e) { - log.debug("update user cache - failed to send notification to update user cache {}", e.getMessage()); - return ActionStatus.OK; - } + } catch (Exception e) { + log.debug("update user cache - failed to send notification to update user cache {}", e.getMessage()); + return ActionStatus.OK; + } } - public DmaapProducer getMsProducer() { return msProducer; } - } 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 e12ac92b51..0f44f413a5 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 @@ -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. @@ -17,14 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; +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 org.apache.commons.codec.binary.Base64; import org.glassfish.jersey.server.ContainerRequest; import org.openecomp.sdc.be.config.Configuration; @@ -40,39 +50,22 @@ import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.web.context.WebApplicationContext; -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.StringTokenizer; - @Priority(10) public class BasicAuthenticationFilter implements ContainerRequestFilter { - - private static LoggerSdcAudit audit = new LoggerSdcAudit(BasicAuthenticationFilter.class); private static final Logger log = Logger.getLogger(BasicAuthenticationFilter.class); private static final String COMPONENT_UTILS_FAILED = "Authentication Filter Failed to get component utils."; private static final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); private static final Configuration.BasicAuthConfig basicAuthConf = configurationManager.getConfiguration().getBasicAuth(); - + private static LoggerSdcAudit audit = new LoggerSdcAudit(BasicAuthenticationFilter.class); + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); @Context private HttpServletRequest sr; - - protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private String realm = "ASDC"; @Override public void filter(ContainerRequestContext requestContext) throws IOException { audit.startLog(requestContext); - if (!basicAuthConf.isEnabled()) { return; } @@ -80,7 +73,6 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter { if (excludedUrls.contains(((ContainerRequest) requestContext).getRequestUri().getPath())) { return; } - String authHeader = requestContext.getHeaderString(Constants.AUTHORIZATION_HEADER); if (authHeader != null) { StringTokenizer st = new StringTokenizer(authHeader); @@ -103,20 +95,18 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter { log.error("Authentication Filter Failed no authorization header"); authRequiredError(requestContext); } - } - private void checkUserCredentials(ContainerRequestContext requestContext, String credentials) { + private void checkUserCredentials(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(); - if (!userName.equals(basicAuthConf.getUserName()) || !password.equals(basicAuthConf.getUserPass())) { log.error("Authentication Failed. Invalid userName or password"); authInvalidPasswordError(requestContext, userName); } - authSuccessful(requestContext, userName); + authSuccessful(requestContext, userName); } else { log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic authentication."); authInvalidHeaderError(requestContext); @@ -128,9 +118,7 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter { if (componentUtils == null) { abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build()); } else { - componentUtils - .auditAuthEvent(requestContext.getUriInfo().getPath(), userName, AuthStatus.AUTH_SUCCESS.toString(), - realm); + componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), userName, AuthStatus.AUTH_SUCCESS.toString(), realm); } } @@ -139,8 +127,7 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter { if (componentUtils == null) { abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build()); } else { - componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), userName, - AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm); + componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), userName, AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, false)); } @@ -149,53 +136,50 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter { private void authInvalidHeaderError(ContainerRequestContext requestContext) { ComponentsUtils componentUtils = getComponentsUtils(); if (componentUtils == null) { - abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build()); + abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build()); } - getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm); + getComponentsUtils() + .auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED_INVALIDE_HEADER); - abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, false)); + abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, false)); } private void authRequiredError(ContainerRequestContext requestContext) { ComponentsUtils componentUtils = getComponentsUtils(); if (componentUtils == null) { - abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build()); + abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build()); } getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_REQUIRED.toString(), realm); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_REQUIRED); - abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, true)); + abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, true)); } private ComponentsUtils getComponentsUtils() { ServletContext context = sr.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(ComponentsUtils.class); } - 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 + "\""); } - return responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); + return responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); } - private void abortWith(ContainerRequestContext requestContext, String message, Response response) { - - audit.logEntry(sr.getRemoteAddr(), - requestContext, + private void abortWith(ContainerRequestContext requestContext, String message, Response response) { + audit.logEntry(sr.getRemoteAddr(), requestContext, // response.getStatusInfo(), - LogLevel.ERROR, - Severity.WARNING, - message, null); + LogLevel.ERROR, Severity.WARNING, message, null); + log.error(message); + audit.clearMyData(); + requestContext.abortWith(response); + } - log.error(message); - audit.clearMyData(); - requestContext.abortWith(response); - } + public enum AuthStatus { + AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java index 49b9fbf5d7..7edd1621b1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java @@ -17,9 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; +import java.io.IOException; +import java.util.function.Supplier; +import javax.annotation.Priority; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; import org.onap.aaf.cadi.Access; import org.onap.aaf.cadi.PropAccess; import org.onap.aaf.cadi.config.Config; @@ -34,24 +43,12 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.springframework.web.context.WebApplicationContext; -import javax.annotation.Priority; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.function.Supplier; - @Priority(2) public class BeCadiServletFilter extends CadiFilter { private static final Logger log = Logger.getLogger(BeCadiServletFilter.class); - private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); private static final String BE_CADI_SERVICE_FILTER = "BeCadiServletFilter: "; - + private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); public BeCadiServletFilter() { super(); @@ -70,7 +67,6 @@ public class BeCadiServletFilter extends CadiFilter { log.debug(BE_CADI_SERVICE_FILTER); } - /** * Use this to pass in a PreContructed CADI Filter, but with initializing... let Servlet do it * @@ -80,7 +76,6 @@ public class BeCadiServletFilter extends CadiFilter { * @throws ServletException */ public BeCadiServletFilter(boolean init, PropAccess access, Object... moreTafLurs) throws ServletException { - super(init, access, moreTafLurs); log.debug(BE_CADI_SERVICE_FILTER); } @@ -88,7 +83,7 @@ public class BeCadiServletFilter extends CadiFilter { private void checkIfNullProperty(String key, String value) { /* When value is null, so not defined in application.properties set nothing in System properties */ - if (value != null) { + if (value != null) { /* Ensure that any properties already defined in System.prop by JVM params won't be overwritten by Spring application.properties values */ System.setProperty(key, System.getProperty(key, value)); @@ -97,26 +92,21 @@ public class BeCadiServletFilter extends CadiFilter { @Override public void init(FilterConfig filterConfig) throws ServletException { - // set some properties in System so that Cadi filter will find its config + // The JVM values set will always overwrite the Spring ones. CadiFilterParams cadiFilterParams = configurationManager.getConfiguration().getCadiFilterParams(); checkIfNullProperty(Config.HOSTNAME, cadiFilterParams.getHostname()); log.debug("BeCadiServletFilter: HOSTNAME", cadiFilterParams.getHostname()); - checkIfNullProperty(Config.CADI_KEYFILE, cadiFilterParams.getCadi_keyfile()); checkIfNullProperty(Config.CADI_LOGLEVEL, cadiFilterParams.getCadi_loglevel()); - - checkIfNullProperty(Config.CADI_LATITUDE, cadiFilterParams.getAFT_LATITUDE()); checkIfNullProperty(Config.CADI_LONGITUDE, cadiFilterParams.getAFT_LONGITUDE()); - checkIfNullProperty(Config.AAF_URL, cadiFilterParams.getAaf_url()); //checkIfNullProperty(Config.AAF_LOCATE_URL, cadiFilterParams.getAafLocateUrl()); checkIfNullProperty(Config.AAF_APPID, cadiFilterParams.getAaf_id()); checkIfNullProperty(Config.AAF_APPPASS, cadiFilterParams.getAaf_password()); checkIfNullProperty(Config.AAF_ENV, cadiFilterParams.getAFT_ENVIRONMENT()); - checkIfNullProperty(Config.CADI_X509_ISSUERS, cadiFilterParams.getCadiX509Issuers()); checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiFilterParams.getCadi_truststore()); checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiFilterParams.getCadi_truststore_password()); @@ -129,10 +119,8 @@ public class BeCadiServletFilter extends CadiFilter { } } - @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (ThreadLocalsHolder.isExternalRequest() && isNeedAuth()) { log.debug("doFilter: {}", request.getContentType()); HttpServletRequest hreq = (HttpServletRequest) request; @@ -150,31 +138,14 @@ public class BeCadiServletFilter extends CadiFilter { return configurationManager.getConfiguration().getAafAuthNeeded(); } - ThreadLocalUtils getThreadLocalUtils(ServletContext context) { return getClassFromWebAppContext(context, () -> ThreadLocalUtils.class); } T getClassFromWebAppContext(ServletContext context, Supplier> businessLogicClassGen) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(businessLogicClassGen.get()); } - - } - - - - - - - - - - - - - - - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeRestrictionAccessFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeRestrictionAccessFilter.java index de8969a310..e40dfe408f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeRestrictionAccessFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeRestrictionAccessFilter.java @@ -17,33 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; +import java.io.IOException; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import org.onap.sdc.security.PortalClient; import org.onap.sdc.security.filters.RestrictionAccessFilter; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.springframework.stereotype.Component; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import java.io.IOException; - @Component("beRestrictionAccessFilter") public class BeRestrictionAccessFilter extends RestrictionAccessFilter { private static final Logger log = Logger.getLogger(RestrictionAccessFilter.class.getName()); - public BeRestrictionAccessFilter(FilterConfiguration configuration, ThreadLocalUtils threadLocalUtils, - PortalClient portalClient) { + public BeRestrictionAccessFilter(FilterConfiguration configuration, ThreadLocalUtils threadLocalUtils, PortalClient portalClient) { super(configuration, threadLocalUtils, portalClient); } @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { if (ThreadLocalsHolder.isInternalRequest()) { super.doFilter(servletRequest, servletResponse, filterChain); } else { 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 c559751515..ea1df86906 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 @@ -17,10 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; import com.google.gson.GsonBuilder; +import java.io.IOException; +import javax.annotation.Priority; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; import org.onap.logging.filter.base.AuditLogContainerFilter; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -39,23 +47,13 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.MDC; import org.springframework.web.context.WebApplicationContext; -import javax.annotation.Priority; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; -import java.io.IOException; - @Provider @Priority(1) public class BeServletFilter extends AuditLogContainerFilter { + private static final Logger log = Logger.getLogger(BeServletFilter.class); @Context private HttpServletRequest sr; - private static final Logger log = Logger.getLogger(BeServletFilter.class); @Override public void filter(ContainerRequestContext requestContext) { @@ -63,7 +61,9 @@ public class BeServletFilter extends AuditLogContainerFilter { try { super.filter(requestContext); // 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 @@ -95,16 +95,14 @@ public class BeServletFilter extends AuditLogContainerFilter { 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()); } writeToJanusGraph(responseContext); - outHttpResponse(responseContext); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); log.debug("Error during response filter: {} ", e); @@ -121,9 +119,8 @@ public class BeServletFilter extends AuditLogContainerFilter { HealingJanusGraphDao janusGraphDao = getJanusGraphDao(); if (janusGraphDao != null) { int status = responseContext.getStatus(); - if (status == Response.Status.OK.getStatusCode() || - status == Response.Status.CREATED.getStatusCode() || - status == Response.Status.NO_CONTENT.getStatusCode()) { + if (status == Response.Status.OK.getStatusCode() || status == Response.Status.CREATED.getStatusCode() + || status == Response.Status.NO_CONTENT.getStatusCode()) { janusGraphDao.commit(); log.debug("Doing commit from filter"); } else { @@ -137,26 +134,24 @@ public class BeServletFilter extends AuditLogContainerFilter { // 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(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, serviceInstanceID); - MDC.put("remoteAddr", sr.getRemoteAddr()); MDC.put("localAddr", sr.getLocalAddr()); } private ComponentsUtils getComponentsUtils() { ServletContext context = this.sr.getSession().getServletContext(); - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(ComponentsUtils.class); } private HealingJanusGraphDao getJanusGraphDao() { ServletContext context = this.sr.getSession().getServletContext(); - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(HealingJanusGraphDao.class); } 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 5ccbb26f93..fe881b3adf 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 @@ -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. @@ -17,11 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +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.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -38,45 +49,27 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.MarkerFactory; import org.springframework.web.context.WebApplicationContext; -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 { - private static LoggerSdcAudit audit = new LoggerSdcAudit(ComponentsAvailabilityFilter.class); - + private static final Logger log = Logger.getLogger(ComponentsAvailabilityFilter.class); + private static LoggerSdcAudit audit = new LoggerSdcAudit(ComponentsAvailabilityFilter.class); @Context protected HttpServletRequest sr; protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static final Logger log = Logger.getLogger(ComponentsAvailabilityFilter.class); @Override public void filter(ContainerRequestContext requestContext) throws IOException { - - audit.startLog(requestContext); - + audit.startLog(requestContext); String requestUrl = requestContext.getUriInfo().getPath(); if (!"healthCheck".equals(requestUrl)) { 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) { @@ -91,7 +84,6 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter { } protected List getBeHealthCheckInfos(ServletContext servletContext) { - List healthCheckInfos = new ArrayList<>(); HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext); healthCheckInfos.add(healthCheckBusinessLogic.getJanusGraphHealthCheck()); @@ -100,7 +92,8 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter { protected ComponentsUtils getComponentsUtils() { ServletContext context = sr.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(ComponentsUtils.class); } @@ -108,34 +101,27 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter { protected void availabilityError(ContainerRequestContext requestContext) { ComponentsUtils componentUtils = getComponentsUtils(); if (componentUtils == null) { - String message = "Components Availability Filter Failed to get component utils."; - abortWith(requestContext, message, Response.status(Status.INTERNAL_SERVER_ERROR).build()); + String message = "Components Availability Filter Failed to get component utils."; + abortWith(requestContext, message, 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(); - abortWith(requestContext, responseFormat.getRequestError().toString(), response); + abortWith(requestContext, responseFormat.getRequestError().toString(), response); } private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(HealthCheckBusinessLogic.class); } - - private void abortWith(ContainerRequestContext requestContext, String message, Response response) { - - audit.logExit(sr.getRemoteAddr(), - requestContext, - response.getStatusInfo(), - LogLevel.ERROR, - Severity.OK, - message, - MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName())); - - log.error(message); - audit.clearMyData(); - requestContext.abortWith(response); - } + private void abortWith(ContainerRequestContext requestContext, String message, Response response) { + audit.logExit(sr.getRemoteAddr(), requestContext, response.getStatusInfo(), LogLevel.ERROR, Severity.OK, message, + MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName())); + log.error(message); + audit.clearMyData(); + requestContext.abortWith(response); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/FilterConfiguration.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/FilterConfiguration.java index 7bd9c46780..70a67758df 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/FilterConfiguration.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/FilterConfiguration.java @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; +import java.util.List; import org.onap.sdc.security.ISessionValidationFilterConfiguration; import org.openecomp.sdc.be.config.Configuration; -import java.util.List; - public class FilterConfiguration implements ISessionValidationFilterConfiguration { protected Configuration config; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/GatewayFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/GatewayFilter.java index 9b9fd6dbcf..c5f0881caa 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/GatewayFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/GatewayFilter.java @@ -17,19 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; -import org.apache.http.HttpStatus; -import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper; -import org.openecomp.sdc.common.api.FilterDecisionEnum; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - +import java.io.IOException; +import java.util.List; +import java.util.stream.Stream; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -39,23 +31,27 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.WebApplicationException; -import java.io.IOException; -import java.util.List; -import java.util.stream.Stream; +import org.apache.http.HttpStatus; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper; +import org.openecomp.sdc.common.api.FilterDecisionEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; @Component("gatewayFilter") public class GatewayFilter implements Filter { + private static final Logger log = Logger.getLogger(BeServletFilter.class); private Configuration.CookieConfig authCookieConf; private Configuration config; - private static final Logger log = Logger.getLogger(BeServletFilter.class); - @Autowired private ThreadLocalUtils threadLocalUtils; @Autowired private ComponentExceptionMapper componentExceptionMapper; - public GatewayFilter(org.openecomp.sdc.be.config.Configuration configuration) { this.authCookieConf = configuration.getAuthCookie(); } @@ -66,7 +62,6 @@ public class GatewayFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { - HttpServletRequest httpRequest = (HttpServletRequest) req; HttpServletResponse httpResponse = (HttpServletResponse) res; try { @@ -77,12 +72,10 @@ public class GatewayFilter implements Filter { } } catch (ComponentException ce) { componentExceptionMapper.writeToResponse(ce, httpResponse); - } catch (WebApplicationException we) { httpResponse.setStatus(we.getResponse().getStatus()); setDefaultHttpParams(httpResponse); httpResponse.getWriter().write(we.getMessage()); - } catch (Exception ex) { httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); setDefaultHttpParams(httpResponse); @@ -106,10 +99,10 @@ public class GatewayFilter implements Filter { } private Boolean isConsumerBusinessLogic() { - return config.getConsumerBusinessLogic(); + return config.getConsumerBusinessLogic(); } + @Override public void destroy() { - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/PortalConfiguration.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/PortalConfiguration.java index 2ed10dc771..7bceebe77a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/PortalConfiguration.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/PortalConfiguration.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; import org.onap.sdc.security.IPortalConfiguration; @@ -32,11 +31,16 @@ public class PortalConfiguration implements IPortalConfiguration { private String uebKey; public PortalConfiguration() throws org.onap.portalsdk.core.onboarding.exception.CipherUtilException { - this.portalUser = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.USER.value()); - this.portalPassword = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(PortalClient.PortalPropertiesEnum.PASSWORD.value()); - this.portalAppName = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(PortalClient.PortalPropertiesEnum.APP_NAME.value()); - this.ecompPortalRestURL = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.ECOMP_REST_URL.value()); - this.uebKey = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.UEB_APP_KEY.value()); + this.portalUser = org.onap.portalsdk.core.onboarding.util.PortalApiProperties + .getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.USER.value()); + this.portalPassword = org.onap.portalsdk.core.onboarding.util.PortalApiProperties + .getProperty(PortalClient.PortalPropertiesEnum.PASSWORD.value()); + this.portalAppName = org.onap.portalsdk.core.onboarding.util.PortalApiProperties + .getProperty(PortalClient.PortalPropertiesEnum.APP_NAME.value()); + this.ecompPortalRestURL = org.onap.portalsdk.core.onboarding.util.PortalApiProperties + .getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.ECOMP_REST_URL.value()); + this.uebKey = org.onap.portalsdk.core.onboarding.util.PortalApiProperties + .getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.UEB_APP_KEY.value()); } @Override @@ -133,4 +137,4 @@ public class PortalConfiguration implements IPortalConfiguration { public String getExtReqReadTimeout() { return null; } -} \ No newline at end of file +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ReqValidationFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ReqValidationFilter.java index 4fc576b79d..faf33dea1e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ReqValidationFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ReqValidationFilter.java @@ -17,9 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; @@ -33,18 +43,6 @@ import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - @Component("reqValidationFilter") public class ReqValidationFilter implements Filter { @@ -53,18 +51,17 @@ public class ReqValidationFilter implements Filter { public ComponentExceptionMapper componentExceptionMapper; @Override - public void init(FilterConfig filterConfig){ - + public void init(FilterConfig filterConfig) { } @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; try { log.debug("Validating User roles - filter"); List validRoles = Arrays.asList(UserRoleEnum.ADMIN.getName(), UserRoleEnum.DESIGNER.getName()); UserContext userContext = ThreadLocalsHolder.getUserContext(); - if (userContext != null && CollectionUtils.isNotEmpty(userContext.getUserRoles())) { Set userRoles = userContext.getUserRoles(); if (!userRoles.stream().anyMatch(role -> validRoles.contains(role))) { @@ -80,6 +77,5 @@ public class ReqValidationFilter implements Filter { @Override public void destroy() { - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ThreadLocalUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ThreadLocalUtils.java index 3df33c5362..d895b694f5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ThreadLocalUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ThreadLocalUtils.java @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.filters; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import javax.servlet.http.HttpServletRequest; import org.onap.sdc.security.AuthenticationCookie; import org.onap.sdc.security.IUsersThreadLocalHolder; import org.onap.sdc.security.PortalClient; @@ -32,31 +35,23 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - public class ThreadLocalUtils implements IUsersThreadLocalHolder { + private static final Logger log = Logger.getLogger(ThreadLocalUtils.class); @Autowired PortalClient portalClient; - @Autowired UserBusinessLogic userBusinessLogic; - private static final Logger log = Logger.getLogger(ThreadLocalUtils.class); - @Override public void setUserContext(AuthenticationCookie authenticationCookie) { UserContext userContext; - userContext = new UserContext(authenticationCookie.getUserID(), authenticationCookie.getRoles(), authenticationCookie.getFirstName(), authenticationCookie.getLastName()); + userContext = new UserContext(authenticationCookie.getUserID(), authenticationCookie.getRoles(), authenticationCookie.getFirstName(), + authenticationCookie.getLastName()); ThreadLocalsHolder.setUserContext(userContext); } - protected void setUserContext(HttpServletRequest httpRequest) { - String user_id = httpRequest.getHeader(Constants.USER_ID_HEADER); if (user_id != null) { String userRolesFromPortal = null; @@ -70,7 +65,9 @@ public class ThreadLocalUtils implements IUsersThreadLocalHolder { } UserContext userContext = new UserContext(user_id, roles, null, null); ThreadLocalsHolder.setUserContext(userContext); - } else log.debug("user_id value in req header is null, userContext will not be initialized"); + } else { + log.debug("user_id value in req header is null, userContext will not be initialized"); + } } protected void setUserContextFromDB(HttpServletRequest httpRequest) { @@ -78,7 +75,9 @@ public class ThreadLocalUtils implements IUsersThreadLocalHolder { //there are some internal request that have no user_id header e.g. healthcheck if (user_id != null) { updateUserContext(user_id); - } else log.debug("user_id value in req header is null, userContext will not be initialized"); + } else { + log.debug("user_id value in req header is null, userContext will not be initialized"); + } } private void updateUserContext(String user_id) { @@ -87,5 +86,4 @@ public class ThreadLocalUtils implements IUsersThreadLocalHolder { UserContext userContext = new UserContext(user_id, roles, user.getFirstName(), user.getLastName()); ThreadLocalsHolder.setUserContext(userContext); } - } 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 98b3c84081..8451caba27 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 @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.impl; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -134,9 +133,9 @@ public class ComponentsUtils { private static final String CONVERT_JSON_TO_OBJECT = "convertJsonToObject"; private static final Logger log = Logger.getLogger(ComponentsUtils.class); private static final String PARTNER_NAME = "UNKNOWN"; + private static LoggerSdcAudit audit = new LoggerSdcAudit(DmaapConsumer.class); private final AuditingManager auditingManager; private final ResponseFormatManager responseFormatManager; - private static LoggerSdcAudit audit = new LoggerSdcAudit(DmaapConsumer.class); @Autowired public ComponentsUtils(AuditingManager auditingManager) { @@ -144,6 +143,55 @@ public class ComponentsUtils { this.responseFormatManager = ResponseFormatManager.getInstance(); } + 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); + } + + private static Set getNodesFiltersToBeDeleted(final Component component, final String componentInstanceName) { + return component.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedCi(ci, componentInstanceName)) + .map(ComponentInstance::getName).collect(Collectors.toSet()); + } + + public static Set getNodesFiltersToBeDeleted(final Component component, final ComponentInstance componentInstance) { + return getNodesFiltersToBeDeleted(component, componentInstance.getName()); + } + + private static boolean isNodeFilterUsingChangedCi(final ComponentInstance componentInstance, final String componentInstanceName) { + if (CollectionUtils.isEmpty(componentInstance.getDirectives())) { + return false; + } + if (componentInstance.getNodeFilter() == null || componentInstance.getNodeFilter().getProperties() == null + || componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition() == null) { + return false; + } + return componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition().stream() + .anyMatch(property -> isPropertyConstraintChangedByCi(property, componentInstanceName)); + } + + private static boolean isPropertyConstraintChangedByCi( + final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, final String componentInstanceName) { + final List constraints = requirementNodeFilterPropertyDataDefinition.getConstraints(); + if (constraints == null) { + return false; + } + return constraints.stream().anyMatch(constraint -> isConstraintChangedByCi(constraint, componentInstanceName)); + } + + private static boolean isConstraintChangedByCi(final String constraint, final String componentInstanceName) { + final UIConstraint uiConstraint = new ConstraintConvertor().convert(constraint); + if (uiConstraint == null || uiConstraint.getSourceType() == null) { + return false; + } + if (!uiConstraint.getSourceType().equals(ConstraintConvertor.PROPERTY_CONSTRAINT)) { + return false; + } + return uiConstraint.getSourceName().equals(componentInstanceName); + } + public AuditingManager getAuditingManager() { return auditingManager; } @@ -167,26 +215,17 @@ public class ComponentsUtils { } } - 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) { + public Either convertJsonToObjectUsingObjectMapper(String data, User user, Class clazz, AuditingActionEnum actionEnum, + ComponentTypeEnum typeEnum) { T component; ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, 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(CONVERT_JSON_TO_OBJECT); @@ -212,15 +251,17 @@ public class ComponentsUtils { } public Either, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus storageOperationStatus) { - return storageOperationStatus.equals(StorageOperationStatus.NOT_FOUND) ? Either.left(Collections.emptyList()) : - Either.right(getResponseFormat(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. + * 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. + * 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 @@ -231,19 +272,21 @@ public class ComponentsUtils { return getResponseFormat(actionStatus); } ResponseFormat responseFormat; - switch (actionStatus) { case COMPONENT_VERSION_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion()); + 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()); + 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()); + responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), + resource.getUniqueId()); break; default: responseFormat = getResponseFormat(actionStatus); @@ -256,12 +299,10 @@ public class ComponentsUtils { if (resourceName == null) { return getResponseFormat(actionStatus); } - ResponseFormat responseFormat; if (actionStatus == ActionStatus.RESOURCE_NOT_FOUND) { responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName); - } - else { + } else { responseFormat = getResponseFormat(actionStatus); } return responseFormat; @@ -271,12 +312,10 @@ public class ComponentsUtils { if (capabilityType == null) { return getResponseFormat(actionStatus); } - ResponseFormat responseFormat; if (actionStatus == ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST) { responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType()); - } - else { + } else { responseFormat = getResponseFormat(actionStatus); } return responseFormat; @@ -286,28 +325,27 @@ public class ComponentsUtils { if (obj == null) { return getResponseFormat(actionStatus); } - ResponseFormat responseFormat = null; if (actionStatus == ActionStatus.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 + .get(0)).getName()); //Arbitray index, all we need is single object return responseFormat; } } log.debug("UNKNOWN TYPE : expecting obj as a non empty List"); - } - else { + } else { responseFormat = getResponseFormat(actionStatus); } 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. + * 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 @@ -349,7 +387,6 @@ public class ComponentsUtils { public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String envName) { ResponseFormat responseFormat; - switch (actionStatus) { case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName); @@ -366,7 +403,6 @@ public class ComponentsUtils { public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) { ResponseFormat responseFormat; - switch (actionStatus) { case RESOURCE_NOT_FOUND: case ARTIFACT_NOT_FOUND: @@ -393,8 +429,6 @@ public class ComponentsUtils { return responseFormat; } - - public ResponseFormat getInvalidContentErrorForConsumerAndAudit(User user, ConsumerDefinition consumer, AuditingActionEnum actionEnum) { ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); log.debug(AUDIT_BEFORE_SENDING_RESPONSE); @@ -405,11 +439,12 @@ public class ComponentsUtils { private 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); + auditComponentAdmin(responseFormat, user, null, actionEnum, typeEnum); return responseFormat; } - public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum, ResourceVersionInfo prevResFields) { + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum, + ResourceVersionInfo prevResFields) { auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum, prevResFields, null, null); } @@ -429,20 +464,15 @@ public class ComponentsUtils { ResourceVersionInfo prevResFields, String currentArtifactUuid, ArtifactDefinition artifactDefinition) { if (actionEnum != null) { int status = responseFormat.getStatus(); - 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); - String message = getMessageString(responseFormat); - String artifactData = buildAuditingArtifactData(artifactDefinition); - if (resource != null) { resourceName = resource.getName(); resourceCurrVersion = resource.getVersion(); @@ -452,30 +482,15 @@ public class ComponentsUtils { if (resource.getResourceType() != null) { resourceType = resource.getResourceType().name(); } - invariantUUID = resource.getInvariantUUID(); - uuid = resource.getUUID(); + invariantUUID = resource.getInvariantUUID(); + uuid = resource.getUUID(); toscaNodeType = resource.getToscaResourceName(); } - - AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory( - actionEnum, - CommonAuditData.newBuilder() - .status(status) - .description(message) - .requestId(ThreadLocalsHolder.getUuid()) - .serviceInstanceId(uuid) - .build(), - new ResourceCommonInfo(resourceName, resourceType), - prevResFields, - ResourceVersionInfo.newBuilder() - .artifactUuid(currentArtifactUuid) - .state(resourceCurrState) - .version(resourceCurrVersion) - .build(), - invariantUUID, - modifier, - artifactData, null, null, toscaNodeType); - + AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(actionEnum, + CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(uuid) + .build(), new ResourceCommonInfo(resourceName, resourceType), prevResFields, + ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).state(resourceCurrState).version(resourceCurrVersion).build(), + invariantUUID, modifier, artifactData, null, null, toscaNodeType); getAuditingManager().auditEvent(factory); } } @@ -492,260 +507,163 @@ public class ComponentsUtils { public void auditDistributionDownload(ResponseFormat responseFormat, DistributionData distributionData) { log.trace("Inside auditing"); int status = responseFormat.getStatus(); - String message = getMessageString(responseFormat); - AuditDistributionDownloadEventFactory factory = new AuditDistributionDownloadEventFactory( - CommonAuditData.newBuilder() - .status(status) - .description(message) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - distributionData); + CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).build(), distributionData); getAuditingManager().auditEvent(factory); } public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData, ResourceCommonInfo resourceCommonInfo, String requestId, String serviceInstanceId) { log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum); - AuditEventFactory factory = new AuditAssetExternalApiEventFactory(actionEnum, - CommonAuditData.newBuilder() - .status(responseFormat.getStatus()) - .description(getMessageString(responseFormat)) - .requestId(requestId) - .serviceInstanceId(serviceInstanceId) - .build(), - resourceCommonInfo, distributionData); - + CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId) + .serviceInstanceId(serviceInstanceId).build(), resourceCommonInfo, distributionData); getAuditingManager().auditEvent(factory); } - public void auditExternalGetAssetList(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData, String requestId) { + public void auditExternalGetAssetList(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData, + String requestId) { log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum); - AuditEventFactory factory = new AuditAssetListExternalApiEventFactory(actionEnum, - CommonAuditData.newBuilder() - .status(responseFormat.getStatus()) - .description(getMessageString(responseFormat)) - .requestId(requestId) - .build(), - distributionData); - + CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId) + .build(), distributionData); getAuditingManager().auditEvent(factory); } - public void auditChangeLifecycleAction(ResponseFormat responseFormat, ComponentTypeEnum componentType, String requestId, - Component component, Component responseObject, DistributionData distributionData, User modifier) { - + public void auditChangeLifecycleAction(ResponseFormat responseFormat, ComponentTypeEnum componentType, String requestId, Component component, + Component responseObject, DistributionData distributionData, User modifier) { String invariantUuid = ""; String serviceInstanceId = ""; ResourceVersionInfo currResourceVersionInfo = null; ResourceVersionInfo prevResourceVersionInfo = null; ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue()); - if (component != null) { prevResourceVersionInfo = buildResourceVersionInfoFromComponent(component); resourceCommonInfo.setResourceName(component.getName()); } - - if (responseObject != null){ + if (responseObject != null) { currResourceVersionInfo = buildResourceVersionInfoFromComponent(responseObject); invariantUuid = responseObject.getInvariantUUID(); serviceInstanceId = responseObject.getUUID(); - } - else if (component != null){ + } else if (component != null) { currResourceVersionInfo = buildResourceVersionInfoFromComponent(component); invariantUuid = component.getInvariantUUID(); serviceInstanceId = component.getUUID(); } - if (prevResourceVersionInfo == null) { - prevResourceVersionInfo = ResourceVersionInfo.newBuilder() - .build(); + prevResourceVersionInfo = ResourceVersionInfo.newBuilder().build(); } if (currResourceVersionInfo == null) { - currResourceVersionInfo = ResourceVersionInfo.newBuilder() - .build(); + currResourceVersionInfo = ResourceVersionInfo.newBuilder().build(); } AuditEventFactory factory = new AuditChangeLifecycleExternalApiEventFactory( - CommonAuditData.newBuilder() - .serviceInstanceId(serviceInstanceId) - .requestId(requestId) - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .build(), - resourceCommonInfo, distributionData, - prevResourceVersionInfo, currResourceVersionInfo, - invariantUuid, modifier); - + CommonAuditData.newBuilder().serviceInstanceId(serviceInstanceId).requestId(requestId).description(getMessageString(responseFormat)) + .status(responseFormat.getStatus()).build(), resourceCommonInfo, distributionData, prevResourceVersionInfo, currResourceVersionInfo, + invariantUuid, modifier); getAuditingManager().auditEvent(factory); } private ResourceVersionInfo buildResourceVersionInfoFromComponent(Component component) { - return ResourceVersionInfo.newBuilder() - .version(component.getVersion()) - .state(component.getLifecycleState().name()) - .build(); + return ResourceVersionInfo.newBuilder().version(component.getVersion()).state(component.getLifecycleState().name()).build(); } - public void auditExternalCrudApi(ResponseFormat responseFormat, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, HttpServletRequest request, - ArtifactDefinition artifactDefinition, String artifactUuid) { + public void auditExternalCrudApi(ResponseFormat responseFormat, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, + HttpServletRequest request, ArtifactDefinition artifactDefinition, String artifactUuid) { log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum); - ResourceVersionInfo currResourceVersionInfo; User modifier = new User(); modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER)); String artifactData = ""; DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI()); String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER); - - if (artifactDefinition == null) { - currResourceVersionInfo = ResourceVersionInfo.newBuilder() - .artifactUuid(artifactUuid) - .build(); - } - else { - currResourceVersionInfo = ResourceVersionInfo.newBuilder() - .artifactUuid(artifactDefinition.getArtifactUUID()) - .version(artifactDefinition.getArtifactVersion()) - .build(); + currResourceVersionInfo = ResourceVersionInfo.newBuilder().artifactUuid(artifactUuid).build(); + } else { + currResourceVersionInfo = ResourceVersionInfo.newBuilder().artifactUuid(artifactDefinition.getArtifactUUID()) + .version(artifactDefinition.getArtifactVersion()).build(); artifactData = buildAuditingArtifactData(artifactDefinition); modifier.setUserId(artifactDefinition.getUserIdLastUpdater()); } AuditEventFactory factory = new AuditCrudExternalApiArtifactEventFactory(actionEnum, - CommonAuditData.newBuilder() - .status(responseFormat.getStatus()) - .description(getMessageString(responseFormat)) - .requestId(requestId) - .build(), - resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), currResourceVersionInfo, - null, modifier, artifactData); - + CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId) + .build(), resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), currResourceVersionInfo, null, modifier, + artifactData); getAuditingManager().auditEvent(factory); } - public boolean isExternalApiEvent(AuditingActionEnum auditingActionEnum){ + public boolean isExternalApiEvent(AuditingActionEnum auditingActionEnum) { return auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE); } public void auditCreateResourceExternalApi(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo, HttpServletRequest request, Resource resource) { - String invariantUuid = null; String serviceInstanceId = null; - User modifier = new User(); modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER)); DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI()); String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER); - ResourceVersionInfo currResourceVersionInfo; - - if( resource != null ){ - currResourceVersionInfo = ResourceVersionInfo.newBuilder() - .state(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()) - .version(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION) - .build(); + if (resource != null) { + currResourceVersionInfo = ResourceVersionInfo.newBuilder().state(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()) + .version(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION).build(); resourceCommonInfo.setResourceName(resource.getName()); invariantUuid = resource.getInvariantUUID(); serviceInstanceId = resource.getUUID(); + } else { + currResourceVersionInfo = ResourceVersionInfo.newBuilder().build(); } - else { - currResourceVersionInfo = ResourceVersionInfo.newBuilder() - .build(); - } - AuditEventFactory factory = new AuditCreateResourceExternalApiEventFactory( - CommonAuditData.newBuilder() - .status(responseFormat.getStatus()) - .description(getMessageString(responseFormat)) - .requestId(requestId) - .serviceInstanceId(serviceInstanceId) - .build(), - resourceCommonInfo, distributionData, - currResourceVersionInfo, invariantUuid, modifier); - + CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId) + .serviceInstanceId(serviceInstanceId).build(), resourceCommonInfo, distributionData, currResourceVersionInfo, invariantUuid, + modifier); getAuditingManager().auditEvent(factory); } - + public void auditCreateServiceExternalApi(ResponseFormat responseFormat, HttpServletRequest request, Component service) { - - String invariantUuid = null; + String invariantUuid = null; String serviceInstanceId = null; - - User modifier = new User(); + User modifier = new User(); modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER)); DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI()); String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER); - - if(null != service) { - invariantUuid = service.getInvariantUUID(); - serviceInstanceId = service.getUUID(); - } - - AuditEventFactory factory = new AuditCreateServiceExternalApiEventFactory( - CommonAuditData.newBuilder() - .status(responseFormat.getStatus()) - .description(getMessageString(responseFormat)) - .requestId(requestId) - .serviceInstanceId(serviceInstanceId) - .build(), - new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), distributionData, invariantUuid, modifier); - + if (null != service) { + invariantUuid = service.getInvariantUUID(); + serviceInstanceId = service.getUUID(); + } + AuditEventFactory factory = new AuditCreateServiceExternalApiEventFactory( + CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId) + .serviceInstanceId(serviceInstanceId).build(), new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), distributionData, + invariantUuid, modifier); getAuditingManager().auditEvent(factory); - } - public void auditExternalActivateService(ResponseFormat responseFormat, DistributionData distributionData, String requestId, String serviceInstanceUuid, User modifier) { + public void auditExternalActivateService(ResponseFormat responseFormat, DistributionData distributionData, String requestId, + String serviceInstanceUuid, User modifier) { AuditEventFactory factory = new AuditActivateServiceExternalApiEventFactory( - CommonAuditData.newBuilder() - .serviceInstanceId(serviceInstanceUuid) - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .requestId(requestId) - .build(), - new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), distributionData, "", modifier); + CommonAuditData.newBuilder().serviceInstanceId(serviceInstanceUuid).description(getMessageString(responseFormat)) + .status(responseFormat.getStatus()).requestId(requestId).build(), new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), + distributionData, "", modifier); getAuditingManager().auditEvent(factory); } - public void auditExternalDownloadArtifact(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo, - DistributionData distributionData, String requestId, String currArtifactUuid, String userId) { + public void auditExternalDownloadArtifact(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo, DistributionData distributionData, + String requestId, String currArtifactUuid, String userId) { User modifier = new User(); modifier.setUserId(userId); - AuditEventFactory factory = new AuditDownloadArtifactExternalApiEventFactory( - CommonAuditData.newBuilder() - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .requestId(requestId) - .build(), - resourceCommonInfo, distributionData, - ResourceVersionInfo.newBuilder() - .artifactUuid(currArtifactUuid) - .build(), - modifier); + CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()).requestId(requestId) + .build(), resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().artifactUuid(currArtifactUuid).build(), modifier); getAuditingManager().auditEvent(factory); } 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(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(","); sb.append(artifactDefinition.getArtifactVersion() != null ? artifactDefinition.getArtifactVersion() : " "); sb.append(","); @@ -754,27 +672,20 @@ public class ComponentsUtils { return sb.toString(); } - public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) { + 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); - AuditEventFactory factory = new AuditCategoryEventFactory(actionEnum, - CommonAuditData.newBuilder() - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - modifier, categoryName, subCategoryName, groupingName, componentType); - + CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()) + .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, categoryName, subCategoryName, groupingName, componentType); getAuditingManager().auditEvent(factory); } 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; @@ -847,9 +758,9 @@ public class ComponentsUtils { case COMPONENT_IS_ARCHIVED: responseEnum = ActionStatus.COMPONENT_IS_ARCHIVED; break; - case DECLARED_INPUT_USED_BY_OPERATION: - responseEnum = ActionStatus.DECLARED_INPUT_USED_BY_OPERATION; - break; + case DECLARED_INPUT_USED_BY_OPERATION: + responseEnum = ActionStatus.DECLARED_INPUT_USED_BY_OPERATION; + break; default: responseEnum = ActionStatus.GENERAL_ERROR; break; @@ -878,7 +789,6 @@ public class ComponentsUtils { public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -906,7 +816,6 @@ public class ComponentsUtils { public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -934,7 +843,6 @@ public class ComponentsUtils { public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -974,11 +882,9 @@ public class ComponentsUtils { public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) { ResponseFormat responseFormat; - if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) { responseFormat = getResponseFormat(actionStatus, resourceInstanceName); - } - else { + } else { responseFormat = getResponseFormat(actionStatus, serviceName); } return responseFormat; @@ -988,8 +894,7 @@ public class ComponentsUtils { ResponseFormat responseFormat; if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) { responseFormat = getResponseFormat(actionStatus, resourceInstanceName); - } - else { + } else { responseFormat = getResponseFormat(actionStatus); } return responseFormat; @@ -997,7 +902,6 @@ public class ComponentsUtils { public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -1028,36 +932,46 @@ public class ComponentsUtils { return responseEnum; } - public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, String comment) { + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, + ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, String comment) { auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, null, comment, null, null); } - public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { - auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), ResourceVersionInfo.newBuilder().build()); + public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, + ComponentTypeEnum typeEnum) { + auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), + ResourceVersionInfo.newBuilder().build()); } - public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum, String comment) { - auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), ResourceVersionInfo.newBuilder().build(), null, - comment, null, null); + public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, + ComponentTypeEnum typeEnum, String comment) { + auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), + ResourceVersionInfo.newBuilder().build(), null, comment, null, null); } - public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum, ResourceVersionInfo prevComponent) { + public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, + ComponentTypeEnum typeEnum, ResourceVersionInfo prevComponent) { auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), prevComponent); } - public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent) { + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, + ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent) { auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, null, null, null, null); } - public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, String comment) { - auditComponent(responseFormat, modifier, null, actionEnum, resourceCommonInfo, ResourceVersionInfo.newBuilder().build(), null, comment, null, null); + public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, + String comment) { + auditComponent(responseFormat, modifier, null, actionEnum, resourceCommonInfo, ResourceVersionInfo.newBuilder().build(), null, comment, null, + null); } - public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent) { + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, + ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent) { auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, currComponent, null, null, null); } - public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent, + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, + ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent, String comment, ArtifactDefinition artifactDefinition, String did) { if (actionEnum != null) { String uuid = null; @@ -1066,13 +980,10 @@ public class ComponentsUtils { String currArtifactUid = null; String currVersion = null; String dcurrStatus = null; - log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum); - String message = getMessageString(responseFormat); int status = responseFormat.getStatus(); String artifactData = buildAuditingArtifactData(artifactDefinition); - if (component != null) { // fields that are filled during creation and might still be empty if (component.getLifecycleState() != null) { @@ -1095,192 +1006,117 @@ public class ComponentsUtils { currVersion = currComponent.getVersion(); } } - AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory( - actionEnum, - CommonAuditData.newBuilder() - .status(status) - .description(message) - .requestId(ThreadLocalsHolder.getUuid()) - .serviceInstanceId(uuid) - .build(), - resourceCommonInfo, prevComponent, - ResourceVersionInfo.newBuilder() - .artifactUuid(currArtifactUid) - .state(currState) - .version(currVersion) - .distributionStatus(dcurrStatus) - .build(), - invariantUUID, - modifier, artifactData, comment, did, null); - + AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(actionEnum, + CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(uuid) + .build(), resourceCommonInfo, prevComponent, + ResourceVersionInfo.newBuilder().artifactUuid(currArtifactUid).state(currState).version(currVersion).distributionStatus(dcurrStatus) + .build(), invariantUUID, modifier, artifactData, comment, did, null); getAuditingManager().auditEvent(factory); } } - public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String status) { + public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, + String status) { auditDistributionEngine(action, environmentName, distributionTopicData, null, null, status); } - - public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String role, String apiKey, String status) { - AuditEventFactory factory = AuditDistributionEngineEventFactoryManager.createDistributionEngineEventFactory(action, - environmentName, distributionTopicData, role, apiKey, status); + public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String role, + String apiKey, String status) { + AuditEventFactory factory = AuditDistributionEngineEventFactoryManager + .createDistributionEngineEventFactory(action, environmentName, distributionTopicData, role, apiKey, status); getAuditingManager().auditEvent(factory); } - - public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID, - String environmentType, String action, String environmentName, String tenantContext) { - AuditEventFactory factory = new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName, - environmentType, action, tenantContext); + public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID, String environmentType, String action, + String environmentName, String tenantContext) { + AuditEventFactory factory = new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName, environmentType, action, + tenantContext); audit.startAuditFetchLog(PARTNER_NAME, DmaapConsumer.class.getName()); - audit.logEntry(LogLevel.INFO, Severity.OK, null, - MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), environmentID); + audit.logEntry(LogLevel.INFO, Severity.OK, null, MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), environmentID); getAuditingManager().auditEvent(factory, audit); } - public void auditDistributionNotification(String serviceUUID, String resourceName, String resourceType, String currVersion, User modifier, String environmentName, String currState, - String topicName, String distributionId, String description, String status, String workloadContext, String tenant) { - + public void auditDistributionNotification(String serviceUUID, String resourceName, String resourceType, String currVersion, User modifier, + String environmentName, String currState, String topicName, String distributionId, String description, + String status, String workloadContext, String tenant) { AuditEventFactory factory = new AuditDistributionNotificationEventFactory( - CommonAuditData.newBuilder() - .serviceInstanceId(serviceUUID) - .status(status) - .description(description) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - new ResourceCommonInfo(resourceName, resourceType), - ResourceVersionInfo.newBuilder() - .state(currState) - .version(currVersion) - .build(), - distributionId, modifier, topicName, - new OperationalEnvAuditData(environmentName, workloadContext, tenant)); - + CommonAuditData.newBuilder().serviceInstanceId(serviceUUID).status(status).description(description) + .requestId(ThreadLocalsHolder.getUuid()).build(), new ResourceCommonInfo(resourceName, resourceType), + ResourceVersionInfo.newBuilder().state(currState).version(currVersion).build(), distributionId, modifier, topicName, + new OperationalEnvAuditData(environmentName, workloadContext, tenant)); getAuditingManager().auditEvent(factory); } public void auditAuthEvent(String url, String user, String authStatus, String realm) { - AuditEventFactory factory = new AuditAuthRequestEventFactory( - CommonAuditData.newBuilder() - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - user, url, realm, authStatus); + AuditEventFactory factory = new AuditAuthRequestEventFactory(CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).build(), + user, url, realm, authStatus); getAuditingManager().auditEvent(factory); } - public void auditDistributionStatusNotification(String distributionId, String consumerId, String topicName, - String resourceUrl, String statusTime, String status, - String errorReason, LoggerSdcAudit audit) { - AuditEventFactory factory = new AuditDistributionStatusEventFactory( - CommonAuditData.newBuilder() - .description(errorReason) - .status(status) - .requestId(distributionId) - .build(), - new DistributionData(consumerId, resourceUrl), - distributionId, topicName, statusTime); - + public void auditDistributionStatusNotification(String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime, + String status, String errorReason, LoggerSdcAudit audit) { + AuditEventFactory factory = new AuditDistributionStatusEventFactory( + CommonAuditData.newBuilder().description(errorReason).status(status).requestId(distributionId).build(), + new DistributionData(consumerId, resourceUrl), distributionId, topicName, statusTime); getAuditingManager().auditEvent(factory, audit); } public void auditGetUebCluster(String consumerId, String status, String description) { AuditEventFactory factory = new AuditGetUebClusterEventFactory( - CommonAuditData.newBuilder() - .description(description) - .status(status) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - consumerId); - + CommonAuditData.newBuilder().description(description).status(status).requestId(ThreadLocalsHolder.getUuid()).build(), consumerId); getAuditingManager().auditEvent(factory); } public void auditMissingInstanceIdAsDistributionEngineEvent(AuditingActionEnum actionEnum, String status) { - AuditEventFactory factory = AuditDistributionEngineEventFactoryManager.createDistributionEngineEventFactory( - actionEnum, "", - DistributionTopicData.newBuilder() - .build(), null, null, status); + AuditEventFactory factory = AuditDistributionEngineEventFactoryManager + .createDistributionEngineEventFactory(actionEnum, "", DistributionTopicData.newBuilder().build(), null, null, status); getAuditingManager().auditEvent(factory); } - - public void auditRegisterOrUnRegisterEvent(AuditingActionEnum action, String consumerId, String apiPublicKey, String envName, String status, String distributionStatus, String notifTopicName, String statusTopicName) { + public void auditRegisterOrUnRegisterEvent(AuditingActionEnum action, String consumerId, String apiPublicKey, String envName, String status, + String distributionStatus, String notifTopicName, String statusTopicName) { String appliedStatus = !StringUtils.isEmpty(status) ? status : distributionStatus; - AuditEventFactory factory = new AuditRegUnregDistributionEngineEventFactory(action, - CommonAuditData.newBuilder() - .requestId(ThreadLocalsHolder.getUuid()) - .status(appliedStatus) - .build(), - DistributionTopicData.newBuilder() - .statusTopic(statusTopicName) - .notificationTopic(notifTopicName) - .build(), - consumerId, apiPublicKey, envName); - + CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).status(appliedStatus).build(), + DistributionTopicData.newBuilder().statusTopic(statusTopicName).notificationTopic(notifTopicName).build(), consumerId, apiPublicKey, + envName); getAuditingManager().auditEvent(factory); } - public void auditServiceDistributionDeployed(String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) { - + public void auditServiceDistributionDeployed(String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, + String desc, User modifier) { AuditEventFactory factory = new AuditDistributionDeployEventFactory( - CommonAuditData.newBuilder() - .requestId(ThreadLocalsHolder.getUuid()) - .serviceInstanceId(serviceUUID) - .status(status) - .description(desc) - .build(), - new ResourceCommonInfo(serviceName, "Service"), - distributionId, - modifier, - serviceVersion); - + CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(serviceUUID).status(status).description(desc) + .build(), new ResourceCommonInfo(serviceName, "Service"), distributionId, modifier, serviceVersion); getAuditingManager().auditEvent(factory); - } - public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) { + public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, + User modifier) { AuditEventFactory factory = new AuditConsumerEventFactory(actionEnum, - CommonAuditData.newBuilder() - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - modifier, consumer); - + CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()) + .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, consumer); getAuditingManager().auditEvent(factory); } public void auditGetUsersList(User user, String details, ResponseFormat responseFormat) { - AuditEventFactory factory = new AuditGetUsersListEventFactory( - CommonAuditData.newBuilder() - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - user, details); + CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()) + .requestId(ThreadLocalsHolder.getUuid()).build(), user, details); getAuditingManager().auditEvent(factory); } - public void auditAdminUserActionAndThrowException(AuditingActionEnum actionEnum, User modifier, User userBefore, - User userAfter, ActionStatus status, String... params) { + public void auditAdminUserActionAndThrowException(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, + ActionStatus status, String... params) { ResponseFormat responseFormat = getResponseFormat(status, params); auditAdminUserAction(actionEnum, modifier, userBefore, userAfter, responseFormat); throw new ByResponseFormatComponentException(responseFormat); } public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) { - AuditEventFactory factory = new AuditUserAdminEventFactory(actionEnum, - CommonAuditData.newBuilder() - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - modifier, userBefore, userAfter); - + CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()) + .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, userBefore, userAfter); getAuditingManager().auditEvent(factory); } @@ -1289,26 +1125,16 @@ public class ComponentsUtils { } public void auditUserAccess(User user, ResponseFormat responseFormat) { - - AuditEventFactory factory = new AuditUserAccessEventFactory(CommonAuditData.newBuilder() - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - user); - + AuditEventFactory factory = new AuditUserAccessEventFactory( + CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()) + .requestId(ThreadLocalsHolder.getUuid()).build(), user); getAuditingManager().auditEvent(factory); } public void auditGetCategoryHierarchy(User user, String details, ResponseFormat responseFormat) { - - AuditEventFactory factory = new AuditGetCategoryHierarchyEventFactory(CommonAuditData.newBuilder() - .description(getMessageString(responseFormat)) - .status(responseFormat.getStatus()) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - user, details); - + AuditEventFactory factory = new AuditGetCategoryHierarchyEventFactory( + CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()) + .requestId(ThreadLocalsHolder.getUuid()).build(), user, details); getAuditingManager().auditEvent(factory); } @@ -1317,22 +1143,24 @@ public class ComponentsUtils { 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()); + 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()); + 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()); + responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, + component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); break; default: responseFormat = getResponseFormat(actionStatus); @@ -1347,7 +1175,6 @@ public class ComponentsUtils { public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -1373,7 +1200,7 @@ public class ComponentsUtils { responseEnum = ActionStatus.OK; break; case ELEMENT_NOT_FOUND: - if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){ + if (elementType != null && elementType == JsonPresentationFields.PROPERTY) { responseEnum = ActionStatus.PROPERTY_NOT_FOUND; } break; @@ -1394,20 +1221,20 @@ public class ComponentsUtils { return responseEnum; } - public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) { - + public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, + NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) { if (additionalInfoParameterInfo == null) { additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); } if (labelOrValue == null) { labelOrValue = AdditionalInformationEnum.None; } - switch (actionStatus) { case COMPONENT_NAME_ALREADY_EXIST: return getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey()); case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: - return getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString()); + return getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), + ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString()); case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: return getResponseFormat(actionStatus, nodeType.name().toLowerCase()); case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED: @@ -1421,7 +1248,6 @@ public class ComponentsUtils { default: return getResponseFormat(actionStatus); } - } public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) { @@ -1430,7 +1256,6 @@ public class ComponentsUtils { public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -1461,7 +1286,6 @@ public class ComponentsUtils { public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -1489,7 +1313,6 @@ public class ComponentsUtils { public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -1523,7 +1346,6 @@ public class ComponentsUtils { return getResponseFormat(actionStatus); } ResponseFormat responseFormat; - switch (actionStatus) { case GROUP_MEMBER_EMPTY: case GROUP_TYPE_ALREADY_EXIST: @@ -1534,23 +1356,19 @@ public class ComponentsUtils { 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 { + } else { responseFormat = getResponseFormat(actionStatus); } return responseFormat; - } public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List properties) { @@ -1558,7 +1376,6 @@ public class ComponentsUtils { return getResponseFormat(actionStatus); } ResponseFormat responseFormat; - switch (actionStatus) { case DATA_TYPE_ALREADY_EXIST: responseFormat = getResponseFormat(actionStatus, dataType.getName()); @@ -1587,7 +1404,6 @@ public class ComponentsUtils { case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST: responseFormat = getResponseFormat(actionStatus, dataType.getName()); break; - default: responseFormat = getResponseFormat(actionStatus); break; @@ -1616,9 +1432,8 @@ public class ComponentsUtils { } public ResponseFormat getResponseFormat(ComponentException exception) { - return exception instanceof ByResponseFormatComponentException ? - getResponseFormat((ByResponseFormatComponentException) exception): - getResponseFormat((ByActionStatusComponentException) exception); + return exception instanceof ByResponseFormatComponentException ? getResponseFormat((ByResponseFormatComponentException) exception) + : getResponseFormat((ByActionStatusComponentException) exception); } public ResponseFormat getResponseFormat(ByResponseFormatComponentException exception) { @@ -1629,10 +1444,8 @@ public class ComponentsUtils { return getResponseFormat(exception.getActionStatus(), exception.getParams()); } - public ActionStatus convertFromStorageResponseForRelationshipType( - StorageOperationStatus storageResponse) { + public ActionStatus convertFromStorageResponseForRelationshipType(StorageOperationStatus storageResponse) { ActionStatus responseEnum; - switch (storageResponse) { case OK: responseEnum = ActionStatus.OK; @@ -1663,93 +1476,35 @@ public class ComponentsUtils { return getResponseFormat(status, exception.getParams()); } - public List convertComponentToUiLeftPaletteComponentObject(List components) { List uiLeftPaletteComponents = new ArrayList<>(); - components.forEach(c-> uiLeftPaletteComponents.add(new UiLeftPaletteComponent(c))); + components.forEach(c -> uiLeftPaletteComponents.add(new UiLeftPaletteComponent(c))); return uiLeftPaletteComponents; } - private static Set getNodesFiltersToBeDeleted(final Component component, - final String componentInstanceName) { - return component.getComponentInstances().stream() - .filter(ci -> isNodeFilterUsingChangedCi(ci, componentInstanceName)) - .map(ComponentInstance::getName).collect(Collectors.toSet()); - } - - public static Set getNodesFiltersToBeDeleted(final Component component, - final ComponentInstance componentInstance) { - return getNodesFiltersToBeDeleted(component, componentInstance.getName()); - } - - private static boolean isNodeFilterUsingChangedCi(final ComponentInstance componentInstance, - final String componentInstanceName) { - if (CollectionUtils.isEmpty(componentInstance.getDirectives())) { - return false; - } - if (componentInstance.getNodeFilter() == null || componentInstance.getNodeFilter().getProperties() == null - || componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition() == null) { - return false; - } - return componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition().stream() - .anyMatch(property -> isPropertyConstraintChangedByCi(property, componentInstanceName)); - } - - private static boolean isPropertyConstraintChangedByCi( - final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, - final String componentInstanceName) { - final List constraints = requirementNodeFilterPropertyDataDefinition.getConstraints(); - if (constraints == null) { - return false; - } - return constraints.stream().anyMatch(constraint -> isConstraintChangedByCi(constraint, componentInstanceName)); - } - - private static boolean isConstraintChangedByCi(final String constraint, - final String componentInstanceName) { - final UIConstraint uiConstraint = new ConstraintConvertor().convert(constraint); - if (uiConstraint == null || uiConstraint.getSourceType() == null) { - return false; - } - if (!uiConstraint.getSourceType().equals(ConstraintConvertor.PROPERTY_CONSTRAINT)) { - return false; - } - return uiConstraint.getSourceName().equals(componentInstanceName); - } - public F toResponseFormat() { return sos -> getResponseFormat(convertFromStorageResponse(sos)); } - - public Optional parseToConstraint(final String componentJson, - final User user, - final ComponentTypeEnum componentTypeEnum) { - final Either uiConstraintResponseFormatEither = - convertJsonToObjectUsingObjectMapper(componentJson, user, UIConstraint.class, - AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); + public Optional parseToConstraint(final String componentJson, final User user, final ComponentTypeEnum componentTypeEnum) { + final Either uiConstraintResponseFormatEither = convertJsonToObjectUsingObjectMapper(componentJson, user, + UIConstraint.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); if (uiConstraintResponseFormatEither.isRight()) { return Optional.empty(); } return Optional.of(uiConstraintResponseFormatEither.left().value()); } - private Either parseToConstraints(final String componentJson, - final User user, - final ComponentTypeEnum componentTypeEnum) { - return convertJsonToObjectUsingObjectMapper(componentJson, user, List.class, AuditingActionEnum.CREATE_RESOURCE, - componentTypeEnum); + private Either parseToConstraints(final String componentJson, final User user, final ComponentTypeEnum componentTypeEnum) { + return convertJsonToObjectUsingObjectMapper(componentJson, user, List.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); } - public List validateAndParseConstraint(final ComponentTypeEnum componentTypeEnum, - final String constraintData, + public List validateAndParseConstraint(final ComponentTypeEnum componentTypeEnum, final String constraintData, final User userModifier) { - final String FAILED_TO_PARSE_CONSTRAINT_DATA = "Failed to Parse Constraint Data {}"; final Either convertResponse = parseToConstraints(constraintData, userModifier, componentTypeEnum); if (convertResponse.isRight()) { - log.error(EcompLoggerErrorCode.DATA_ERROR, FAILED_TO_PARSE_CONSTRAINT_DATA, constraintData, - convertResponse.right().value()); + log.error(EcompLoggerErrorCode.DATA_ERROR, FAILED_TO_PARSE_CONSTRAINT_DATA, constraintData, convertResponse.right().value()); return Collections.emptyList(); } final List> uiConstraintsMaps = (List>) convertResponse.left().value(); @@ -1757,10 +1512,7 @@ public class ComponentsUtils { log.error(EcompLoggerErrorCode.DATA_ERROR, FAILED_TO_PARSE_CONSTRAINT_DATA, constraintData); return Collections.emptyList(); } - - return uiConstraintsMaps.stream().map(dataMap -> new com.fasterxml.jackson.databind.ObjectMapper() - .convertValue(dataMap, UIConstraint.class)).collect(Collectors.toList()); + return uiConstraintsMaps.stream().map(dataMap -> new com.fasterxml.jackson.databind.ObjectMapper().convertValue(dataMap, UIConstraint.class)) + .collect(Collectors.toList()); } - - } 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 index 6ef64d4f24..f34dbd35e6 100644 --- 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 @@ -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. @@ -17,12 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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.merge.instance.DataForMergeHolder; @@ -37,21 +43,11 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Service; -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; - 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(); @@ -68,14 +64,15 @@ public class ForwardingPathUtils { } private void initNodeToCP(ComponentInstance ci, SetMultimap nodeToCP) { - if (ci.getCapabilities() == null){ + if (ci.getCapabilities() == null) { return; } Set capabilities = ci.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); if (!CollectionUtils.isNotEmpty(capabilities)) { return; } - Set forwarderCapabilities = capabilities.stream().filter(capabilityDefinition -> capabilityDefinition.getType().equals(FORWARDER_CAPABILITY)).collect(Collectors.toSet()); + Set forwarderCapabilities = capabilities.stream() + .filter(capabilityDefinition -> capabilityDefinition.getType().equals(FORWARDER_CAPABILITY)).collect(Collectors.toSet()); if (!CollectionUtils.isNotEmpty(forwarderCapabilities)) { return; } @@ -83,11 +80,9 @@ public class ForwardingPathUtils { forwarderCapabilities.forEach(fc -> { NameIdPair capability = new NameIdPair(fc.getName(), fc.getName(), fc.getOwnerId()); nodeToCP.put(node, capability); - }); - + }); } - private void handleRelDef(Set relations, SetMultimap nodeToCP) { nodeToCP.keySet().forEach(fromNode -> { NameIdPairWrapper nameIdPairWrapper = new NameIdPairWrapper(); @@ -98,12 +93,10 @@ public class ForwardingPathUtils { 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(this::createWrapper).collect(Collectors.toList()); wrappers.forEach(cpOptionWrapper -> { @@ -118,71 +111,58 @@ public class ForwardingPathUtils { return nameIdPairWrapper; } - private Map> toMap(SetMultimap nodeToCP) { Map> retVal = new HashMap<>(); nodeToCP.asMap().forEach((nameIdPair, nameIdPairs) -> retVal.put(nameIdPair, new HashSet<>(nameIdPairs))); return retVal; } - - public Set findForwardingPathNamesToDeleteOnComponentInstanceDeletion(Service containerService, - String componentInstanceId) { + 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)) + 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() + 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); + 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) { + 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)); + .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()); + 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()); + 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) { + private ForwardingPathElementDataDefinition updateElement(ForwardingPathElementDataDefinition element, String oldCI, String newCI) { ForwardingPathElementDataDefinition retVal = new ForwardingPathElementDataDefinition(element); if (retVal.getFromNode().equals(oldCI)) { retVal.setFromNode(newCI); @@ -190,87 +170,66 @@ public class ForwardingPathUtils { if (retVal.getToNode().equals(oldCI)) { retVal.setToNode(newCI); } - if (Objects.equals(retVal.getToCPOriginId(),oldCI )) { + if (Objects.equals(retVal.getToCPOriginId(), oldCI)) { retVal.setToCPOriginId(newCI); } - if (Objects.equals(retVal.getFromCPOriginId(),oldCI)) { + 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() + 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 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){ + if (newCI.getCapabilities() == null) { return false; } - return newCI.getCapabilities().values() - .stream() - .flatMap(List::stream) - .anyMatch(c -> c.getName().equals(capabilityID)); + return newCI.getCapabilities().values().stream().flatMap(List::stream).anyMatch(c -> c.getName().equals(capabilityID)); } - private boolean elementContainsCIAndDoesNotContainForwarder( - ForwardingPathDataDefinition forwardingPathDataDefinition, - String oldCIId, Component newCI) { - return forwardingPathDataDefinition.getPathElements() - .getListToscaDataDefinition().stream() + 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())); + 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())); } - public Set updateComponentInstanceName(Collection forwardingPathDataDefinitions, - String oldName, String newName){ - return forwardingPathDataDefinitions.stream().filter(fp -> shouldRenameCI(fp,oldName)). - map(forwardingPathDataDefinition -> renamePathCI(forwardingPathDataDefinition,oldName,newName)) - .collect(Collectors.toSet()); - + String oldName, String newName) { + return forwardingPathDataDefinitions.stream().filter(fp -> shouldRenameCI(fp, oldName)) + .map(forwardingPathDataDefinition -> renamePathCI(forwardingPathDataDefinition, oldName, newName)).collect(Collectors.toSet()); } - public boolean shouldRenameCI(ForwardingPathDataDefinition forwardingPathDataDefinitions, - String oldName){ + public boolean shouldRenameCI(ForwardingPathDataDefinition forwardingPathDataDefinitions, String oldName) { return forwardingPathDataDefinitions.getPathElements().getListToscaDataDefinition().stream() .anyMatch(pe -> pe.getToNode().equals(oldName) || pe.getFromNode().equals(oldName)); } - public ForwardingPathDataDefinition renamePathCI(ForwardingPathDataDefinition forwardingPathDataDefinitions, - String oldName, String newName){ - forwardingPathDataDefinitions.getPathElements().getListToscaDataDefinition().stream() - .forEach(pe -> renamePathCI(pe,oldName, newName)); + public ForwardingPathDataDefinition renamePathCI(ForwardingPathDataDefinition forwardingPathDataDefinitions, String oldName, String newName) { + forwardingPathDataDefinitions.getPathElements().getListToscaDataDefinition().stream().forEach(pe -> renamePathCI(pe, oldName, newName)); return forwardingPathDataDefinitions; } - public void renamePathCI(ForwardingPathElementDataDefinition pathElementDataDefinition, - String oldName, String newName){ - if (pathElementDataDefinition.getFromNode().equals(oldName)){ + public void renamePathCI(ForwardingPathElementDataDefinition pathElementDataDefinition, String oldName, String newName) { + if (pathElementDataDefinition.getFromNode().equals(oldName)) { pathElementDataDefinition.setFromNode(newName); } - if(pathElementDataDefinition.getToNode().equals(oldName)){ + if (pathElementDataDefinition.getToNode().equals(oldName)) { pathElementDataDefinition.setToNode(newName); } - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServiceFilterUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServiceFilterUtils.java index e6d7df62cc..866affc509 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServiceFilterUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServiceFilterUtils.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.impl; import java.util.List; @@ -33,56 +32,45 @@ import org.openecomp.sdc.be.ui.model.UIConstraint; public class ServiceFilterUtils { - private ServiceFilterUtils() { } - - public static boolean isNodeFilterAffectedByPropertyRemoval(Service service, String ciName, String propertyName) { + public static boolean isNodeFilterAffectedByPropertyRemoval(Service service, String ciName, String propertyName) { return service.getComponentInstances().stream().filter(ci -> ci.getNodeFilter() != null) - .anyMatch(ci -> propertyIsUsedInCI(ci, ciName, propertyName)); + .anyMatch(ci -> propertyIsUsedInCI(ci, ciName, propertyName)); } - private static boolean propertyIsUsedInCI(ComponentInstance ci, String ciName, String propertyName) { if (CollectionUtils.isEmpty(ci.getDirectives())) { return false; } if (ci.getNodeFilter() == null || ci.getNodeFilter().getProperties() == null - || ci.getNodeFilter().getProperties().getListToscaDataDefinition() == null) { + || ci.getNodeFilter().getProperties().getListToscaDataDefinition() == null) { return false; } - return ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream() - .flatMap(prop -> prop.getConstraints().stream()).map(String::new) - .filter(constraint -> new ConstraintConvertor().convert(constraint).getSourceType() - .equals(ConstraintConvertor.PROPERTY_CONSTRAINT)) - .anyMatch(constraintStr -> { - UIConstraint uiConstraint = new ConstraintConvertor().convert(constraintStr); - return uiConstraint.getSourceName().equals(ciName) && uiConstraint.getValue().equals(propertyName); - }); - + return ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream().flatMap(prop -> prop.getConstraints().stream()) + .map(String::new) + .filter(constraint -> new ConstraintConvertor().convert(constraint).getSourceType().equals(ConstraintConvertor.PROPERTY_CONSTRAINT)) + .anyMatch(constraintStr -> { + UIConstraint uiConstraint = new ConstraintConvertor().convert(constraintStr); + return uiConstraint.getSourceName().equals(ciName) && uiConstraint.getValue().equals(propertyName); + }); } - public static Map getRenamedNodesFilter(Service service, String oldName, - String newName) { + public static Map getRenamedNodesFilter(Service service, String oldName, String newName) { return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedCi(ci, oldName)) - .map(ci -> renameOldCiNames(ci, oldName, newName)) - .collect(Collectors.toMap(Pair::getValue0, Pair::getValue1)); + .map(ci -> renameOldCiNames(ci, oldName, newName)).collect(Collectors.toMap(Pair::getValue0, Pair::getValue1)); } - private static Pair renameOldCiNames(ComponentInstance ci, String oldName, - String newName) { + private static Pair renameOldCiNames(ComponentInstance ci, String oldName, String newName) { ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream() - .filter(property -> isPropertyConstraintChangedByCi(property, oldName)) - .forEach(property -> renamePropertyCiNames(property, oldName, newName)); - + .filter(property -> isPropertyConstraintChangedByCi(property, oldName)) + .forEach(property -> renamePropertyCiNames(property, oldName, newName)); return new Pair<>(ci.getUniqueId(), ci.getNodeFilter()); } - private static void renamePropertyCiNames(RequirementNodeFilterPropertyDataDefinition property, String oldName, - String newName) { - final List constraints = property.getConstraints().stream().map(getConstraintString(oldName, newName)) - .collect(Collectors.toList()); + private static void renamePropertyCiNames(RequirementNodeFilterPropertyDataDefinition property, String oldName, String newName) { + final List constraints = property.getConstraints().stream().map(getConstraintString(oldName, newName)).collect(Collectors.toList()); property.setConstraints(constraints); } @@ -97,34 +85,29 @@ public class ServiceFilterUtils { }; } - public static Set getNodesFiltersToBeDeleted(Service service, String ciName) { - return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedCi(ci, ciName)) - .map(ComponentInstance::getName).collect(Collectors.toSet()); + return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedCi(ci, ciName)).map(ComponentInstance::getName) + .collect(Collectors.toSet()); } - - public static Set getNodesFiltersToBeDeleted(Service service, ComponentInstance inCi) { return getNodesFiltersToBeDeleted(service, inCi.getName()); } - - private static boolean isNodeFilterUsingChangedCi(ComponentInstance ci, String name) { if (CollectionUtils.isEmpty(ci.getDirectives())) { return false; } if (ci.getNodeFilter() == null || ci.getNodeFilter().getProperties() == null - || ci.getNodeFilter().getProperties().getListToscaDataDefinition() == null) { + || ci.getNodeFilter().getProperties().getListToscaDataDefinition() == null) { return false; } return ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream() - .anyMatch(property -> isPropertyConstraintChangedByCi(property, name)); + .anyMatch(property -> isPropertyConstraintChangedByCi(property, name)); } - private static boolean isPropertyConstraintChangedByCi( - RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, String name) { + private static boolean isPropertyConstraintChangedByCi(RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, + String name) { List constraints = requirementNodeFilterPropertyDataDefinition.getConstraints(); if (constraints == null) { return false; @@ -144,8 +127,8 @@ public class ServiceFilterUtils { } public static Set getNodesFiltersToBeDeleted(Service service, InputDefinition changedInput) { - return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedInput(ci, changedInput)) - .map(ComponentInstance::getName).collect(Collectors.toSet()); + return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedInput(ci, changedInput)).map(ComponentInstance::getName) + .collect(Collectors.toSet()); } private static boolean isNodeFilterUsingChangedInput(ComponentInstance ci, InputDefinition changedInput) { @@ -153,12 +136,11 @@ public class ServiceFilterUtils { return false; } return ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream() - .anyMatch(property -> isPropertyConstraintChangedByInput(property, changedInput)); + .anyMatch(property -> isPropertyConstraintChangedByInput(property, changedInput)); } - private static boolean isPropertyConstraintChangedByInput( - RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, - InputDefinition changedInput) { + private static boolean isPropertyConstraintChangedByInput(RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, + InputDefinition changedInput) { List constraints = requirementNodeFilterPropertyDataDefinition.getConstraints(); return constraints.stream().anyMatch(constraint -> isConstraintChangedByInput(constraint, changedInput)); } @@ -170,5 +152,4 @@ public class ServiceFilterUtils { } return uiConstraint.getValue().equals(changedInput.getName()); } - } 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 70bfd60751..6941504189 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 @@ -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. @@ -17,24 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.impl; import com.google.gson.Gson; +import javax.annotation.Resource; import lombok.Getter; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.springframework.stereotype.Component; -import javax.annotation.Resource; - @Component("servletUtils") @Getter public class ServletUtils { + @Resource private ComponentsUtils componentsUtils; - private Gson gson = new Gson(); - @Resource private UserBusinessLogic userAdmin; } 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 02759289b2..3690d71444 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 @@ -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. @@ -17,19 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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) { - return WebApplicationContextUtils.getWebApplicationContext(context); } - } 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 d800f35367..7d4070a7ac 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 @@ -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. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.info; import lombok.Getter; @@ -31,7 +30,9 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; public class ArtifactDefinitionInfo { private String uniqueId; - /** Specifies the display name of the artifact. */ + /** + * Specifies the display name of the artifact. + */ private String artifactName; private String artifactDisplayName; private String artifactVersion; @@ -45,3 +46,4 @@ public class ArtifactDefinitionInfo { artifactUUID = artifactDefinition.getArtifactUUID(); } } + 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 ab088ec3d8..2fedcc3b28 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import com.google.gson.Gson; @@ -50,10 +49,10 @@ import org.openecomp.sdc.exception.ResponseFormat; @Setter @NoArgsConstructor public class ArtifactTemplateInfo { + + public static final String CSAR_ARTIFACT = "artifacts"; private static final Logger log = Logger.getLogger(ArtifactTemplateInfo.class); private static final Gson gson = new Gson(); - public static final String CSAR_ARTIFACT = "artifacts"; - private static final String ARTIFACT_TEMPLATE_TYPE = "type"; private static final String FILE_NAME = "fileName"; private static final String ARTIFACT_TEMPLATE_ENV = "env"; @@ -64,14 +63,12 @@ public class ArtifactTemplateInfo { private static final String CSAR_VOLUME = "volume"; private static final String CSAR_NESTED = "nested"; private static final String DESC = "description"; - private String type; private String fileName; private String env; private boolean base; private String groupName; private String description; - private List relatedArtifactsInfo; public ArtifactTemplateInfo(String type, String fileName, String env, List relatedArtifactsInfo) { @@ -81,14 +78,14 @@ public class ArtifactTemplateInfo { this.relatedArtifactsInfo = relatedArtifactsInfo; } - public static Either createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type, Map o, List createdArtifactTemplateInfoList, - ArtifactTemplateInfo parentArtifact) { + 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(ARTIFACT_TEMPLATE_TYPE)) { resourceInfo.setType((String) artifactTemplateMap.get(ARTIFACT_TEMPLATE_TYPE)); @@ -104,8 +101,7 @@ public class ArtifactTemplateInfo { String envStr = ""; if (envObj instanceof String) { envStr = (String) envObj; - } - else if (envObj instanceof Map) { + } else if (envObj instanceof Map) { Map envMap = (Map) envObj; if (envMap.containsKey(FILE_NAME)) { envStr = (String) envMap.get(FILE_NAME); @@ -118,57 +114,45 @@ public class ArtifactTemplateInfo { } else { resourceInfo.setDescription((String) artifactTemplateMap.get(FILE_NAME)); } - boolean artifactTypeExist = false; String correctType; if (type.equalsIgnoreCase(CSAR_NESTED)) { correctType = ArtifactTypeEnum.HEAT_NESTED.getType(); - } - else if (type.equalsIgnoreCase(CSAR_VOLUME)) { + } else if (type.equalsIgnoreCase(CSAR_VOLUME)) { correctType = ArtifactTypeEnum.HEAT_VOL.getType(); - } - else if (type.equalsIgnoreCase(CSAR_NETWORK)) { + } else if (type.equalsIgnoreCase(CSAR_NETWORK)) { correctType = ArtifactTypeEnum.HEAT_NET.getType(); - } - else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){ - if( parentArtifact != null) { + } else if (type.equalsIgnoreCase(CSAR_ARTIFACT)) { + if (parentArtifact != null) { correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); - } - else { + } else { correctType = resourceInfo.type; } - } - else if (type.equalsIgnoreCase(CSAR_HEAT)) { + } else if (type.equalsIgnoreCase(CSAR_HEAT)) { correctType = ArtifactTypeEnum.HEAT.getType(); - } - else if (type.equalsIgnoreCase(CSAR_HELM)) { + } else if (type.equalsIgnoreCase(CSAR_HELM)) { correctType = ArtifactTypeEnum.HELM.getType(); - } - else { + } 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()); + 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); + 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()); @@ -186,7 +170,8 @@ public class ArtifactTemplateInfo { 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); + Either relatedArtifact = ArtifactTemplateInfo + .createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo); if (relatedArtifact.isRight()) { return relatedArtifact; } @@ -200,32 +185,40 @@ public class ArtifactTemplateInfo { return Either.left(resourceInfo); } - private static Either validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, List createdArtifactTemplateInfoList, ArtifactTemplateInfo parentArtifact) { - + private static Either validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, + List createdArtifactTemplateInfoList, + ArtifactTemplateInfo parentArtifact) { if (parentArtifact == null) { - if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) + 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)); + 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()) + if (relatedArtifacts == null || relatedArtifacts.isEmpty()) { return Either.left(true); + } for (ArtifactTemplateInfo relatedArtifact : relatedArtifacts) { - if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && relatedArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), parentArtifact.getFileName())); + if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && 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) { - + private static Either validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, + ArtifactTemplateInfo parentArtifact) { if (parentArtifact == null) { return Either.left(true); } @@ -233,78 +226,99 @@ public class ArtifactTemplateInfo { return Either.left(true); } if (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())); + 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 ((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())) { + 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())); + 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()) && 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()) + 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())) + } + 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())) { + 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() && !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())); + 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()) + if (status.isRight()) { return status; + } } return Either.left(true); } private static Either, ActionStatus> getDeploymentArtifactTypes(final NodeTypeEnum parentType) { - final List deploymentArtifacts; - final List artifactConfigurationList = - ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts(); - + final List artifactConfigurationList = ConfigurationManager.getConfigurationManager().getConfiguration() + .getArtifacts(); if (parentType == NodeTypeEnum.Service) { - deploymentArtifacts = artifactConfigurationList.stream() - .filter(artifactConfiguration -> - artifactConfiguration.hasSupport(ArtifactGroupTypeEnum.DEPLOYMENT) - && artifactConfiguration.hasSupport(ComponentType.SERVICE)) - .collect(Collectors.toList()); + deploymentArtifacts = artifactConfigurationList.stream().filter( + artifactConfiguration -> artifactConfiguration.hasSupport(ArtifactGroupTypeEnum.DEPLOYMENT) && artifactConfiguration + .hasSupport(ComponentType.SERVICE)).collect(Collectors.toList()); } else { - deploymentArtifacts = artifactConfigurationList.stream() - .filter(artifactConfiguration -> - artifactConfiguration.hasSupport(ArtifactGroupTypeEnum.DEPLOYMENT) - && artifactConfiguration.hasSupport(ComponentType.RESOURCE)) - .collect(Collectors.toList()); + deploymentArtifacts = artifactConfigurationList.stream().filter( + artifactConfiguration -> artifactConfiguration.hasSupport(ArtifactGroupTypeEnum.DEPLOYMENT) && artifactConfiguration + .hasSupport(ComponentType.RESOURCE)).collect(Collectors.toList()); } final List artifactTypes = new ArrayList<>(); if (CollectionUtils.isNotEmpty(deploymentArtifacts)) { @@ -315,7 +329,6 @@ public class ArtifactTemplateInfo { }); return Either.left(artifactTypes); } - return Either.right(ActionStatus.GENERAL_ERROR); } 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 7ef74a18ca..0a0915649a 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 @@ -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. @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; +import java.util.List; import lombok.Getter; import lombok.Setter; import org.openecomp.sdc.be.model.ArtifactType; -import java.util.List; - @Getter @Setter public class ArtifactTypesInfo { + private Integer heatDefaultTimeout = 60; private List artifactTypes; } 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 02e1238e33..7997ba47c9 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 @@ -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. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.info; import lombok.AllArgsConstructor; @@ -32,6 +31,7 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; @Setter @AllArgsConstructor public class CreateAndAssotiateInfo { + private ComponentInstance node; private RequirementCapabilityRelDef 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 0850be8806..524cd318ef 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 @@ -19,30 +19,26 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.info; +import java.util.Arrays; +import java.util.Optional; import lombok.AllArgsConstructor; import lombok.Getter; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.Arrays; -import java.util.Optional; - @Getter @AllArgsConstructor public enum DistributionStatus { DEPLOYED("Deployed", "DEPLOYED"); - + private static final Logger log = Logger.getLogger(DistributionStatus.class); private String name; private String auditingStatus; - private static final Logger log = Logger.getLogger(DistributionStatus.class); - public static DistributionStatus getStatusByAuditingStatusName(String auditingStatus) { - Optional distributionStatus = Arrays.stream(values()) - .filter(value -> value.getAuditingStatus().equals(auditingStatus)).findAny(); - if (!distributionStatus.isPresent()){ + Optional distributionStatus = Arrays.stream(values()).filter(value -> value.getAuditingStatus().equals(auditingStatus)) + .findAny(); + if (!distributionStatus.isPresent()) { log.debug("No DistributionStatus is mapped to name {}", auditingStatus); } // it should be replaced by some exception handling. Keeping it only for the purpose of backward compatibility 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 9fc747680f..e730ae2d33 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 @@ -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. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.info; import lombok.Getter; 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 d57437fc76..acd0c47e38 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import java.util.List; @@ -27,5 +26,6 @@ import lombok.Setter; @Getter @Setter public class DistributionStatusListResponse { + private List distributionStatusList; } 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 f7bb1ea64c..a203def675 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 @@ -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. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.info; import lombok.AllArgsConstructor; @@ -32,6 +31,7 @@ import lombok.Setter; @NoArgsConstructor @AllArgsConstructor public class DistributionStatusOfServiceInfo { + private String distributionID; private String timestamp; private String userId; 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 23a71c6c9d..b5e97585f0 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import java.util.List; @@ -27,5 +26,6 @@ import lombok.Setter; @Getter @Setter public class DistributionStatusOfServiceListResponce { + private List distributionStatusOfServiceList; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GenericArtifactQueryInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GenericArtifactQueryInfo.java index 7aa0070311..fb85273199 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GenericArtifactQueryInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GenericArtifactQueryInfo.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import java.util.Set; @@ -31,6 +30,7 @@ import lombok.Setter; @AllArgsConstructor @NoArgsConstructor public class GenericArtifactQueryInfo { + private Set fields; private String parentId; private String artifactUniqueId; 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 54920ea475..79b88606d8 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 @@ -21,6 +21,10 @@ */ package org.openecomp.sdc.be.info; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -28,46 +32,38 @@ import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupProperty; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; @Getter @Setter public class GroupDefinitionInfo { - private String name; + private String name; private String description; - // 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; - private Boolean isBase = null; - // artifacts - list of artifact uid. All artifacts in the group must already + // be uploaded to the VF @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private List artifacts; - private Map members; - @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private List properties; @@ -98,19 +94,19 @@ public class GroupDefinitionInfo { } public List getArtifacts() { - return (artifacts==null) ? null : new ArrayList<>(artifacts); + return (artifacts == null) ? null : new ArrayList<>(artifacts); } - public List getProperties() { - return (properties==null) ? null : new ArrayList<>(properties); + public void setArtifacts(List artifacts) { + this.artifacts = (artifacts == null) ? null : new ArrayList<>(artifacts); } - public void setArtifacts(List artifacts) { - this.artifacts = (artifacts==null) ? null : new ArrayList<>(artifacts); + public List getProperties() { + return (properties == null) ? null : new ArrayList<>(properties); } public void setProperties(List properties) { - this.properties = (properties==null) ? null : new ArrayList<>(properties); + this.properties = (properties == null) ? null : new ArrayList<>(properties); } @Override 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 ddee613dd5..0559ee71e1 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import lombok.Getter; @@ -26,6 +25,7 @@ import lombok.Setter; @Getter @Setter public class GroupTemplateInfo { + private String groupName; private boolean base; private 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 4ae38f9f80..d97da412f8 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 @@ -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. @@ -17,26 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.Setter; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.model.ArtifactDefinition; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.model.ArtifactDefinition; public class MergedArtifactInfo { - @Getter @Setter(AccessLevel.NONE) + @Getter + @Setter(AccessLevel.NONE) private List createdArtifact; - @Getter @Setter + @Getter + @Setter private ArtifactTemplateInfo jsonArtifactTemplate; private Set parsedArtifactsNames; @@ -63,21 +63,20 @@ public class MergedArtifactInfo { List resList = new ArrayList<>(); for (ArtifactDefinition artifactDefinition : createdArtifact) { boolean isDissotiate = true; - if(parsedArtifactsNames.contains(artifactDefinition.getArtifactName())){ + if (parsedArtifactsNames.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()){ + } 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(parsedArtifactsNames.contains(generatedFromArt.getArtifactName())){ + if (parsedArtifactsNames.contains(generatedFromArt.getArtifactName())) { isDissotiate = false; } - } - else{ + } else { isDissotiate = true; } - } } if (isDissotiate) { @@ -87,14 +86,12 @@ public class MergedArtifactInfo { isDeleted = true; break; } - } - if (!isDeleted) + if (!isDeleted) { resList.add(artifactDefinition); + } } - } - return resList; } @@ -112,16 +109,14 @@ public class MergedArtifactInfo { return resList; } - private void getUpdateArtifactsInGroup(List> resList, List jsonArtifacts) { - + 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); @@ -130,7 +125,6 @@ public class MergedArtifactInfo { } private void getNewArtifactsInGroup(List resList, List jsonArtifacts) { - for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { boolean isNewArtifact = true; for (ArtifactDefinition artifactDefinition : createdArtifact) { @@ -138,8 +132,9 @@ public class MergedArtifactInfo { isNewArtifact = false; } } - if (isNewArtifact) + if (isNewArtifact) { resList.add(artifactTemplateInfo); + } List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { getNewArtifactsInGroup(resList, relatedArtifacts); @@ -148,7 +143,6 @@ public class MergedArtifactInfo { } private void createArtifactsGroupSet(List parsedGroupTemplateList, Set parsedArtifactsName) { - for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { parsedArtifactsName.add(parsedGroupTemplate.getFileName()); List relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); 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 index a4d7db2e78..53d722d53b 100644 --- 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 @@ -21,20 +21,20 @@ */ package org.openecomp.sdc.be.info; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; 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; - @Getter @Setter @AllArgsConstructor public class NodeTypeInfoToUpdateArtifacts { + private String nodeName; private Map>> 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 index daeea5e18a..a795b161c5 100644 --- 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 @@ -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. @@ -17,65 +17,54 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 java.io.IOException; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.IOException; - @Getter @Setter public final class OperationalEnvInfo { - @JsonIgnore - private static ObjectMapper objectMapper = new ObjectMapper(); - + @JsonIgnore private static final Logger logger = Logger.getLogger(OperationalEnvInfo.class); - + @JsonIgnore + private static ObjectMapper objectMapper = new ObjectMapper(); @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 static OperationalEnvInfo createFromJson(String json) throws IOException { + return objectMapper.readValue(json, OperationalEnvInfo.class); + } + @Override public String toString() { try { return objectMapper.writeValueAsString(this); - } - catch (JsonProcessingException e) { + } 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 index abea08353b..eac4e67a4b 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,7 +29,6 @@ public final class RelatedToProperty { @JsonProperty("property-key") private String propertyKey; - @JsonProperty("property-value") private String 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 index 3c5f1e2ec3..a93ab15526 100644 --- 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 @@ -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. @@ -17,11 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.ArrayList; import java.util.List; import lombok.AccessLevel; @@ -31,33 +29,29 @@ import lombok.Setter; @Getter @Setter public final class Relationship { - + @JsonProperty("related-to") private String relatedTo; - - @JsonProperty(value="relationship-label") + @JsonProperty(value = "relationship-label") private String relationshipLabel; - - @JsonProperty(value="related-link", required=false) + @JsonProperty(value = "related-link", required = false) private String relatedLink; - @JsonProperty("relationship-data") @Getter(AccessLevel.NONE) private List relationshipData; - @JsonProperty("related-to-property") @Getter(AccessLevel.NONE) private List relatedToProperty; public List getRelationshipData() { - if(relationshipData == null) { + if (relationshipData == null) { relationshipData = new ArrayList<>(); } return relationshipData; } public List getRelatedToProperty() { - if(relatedToProperty == null) { + if (relatedToProperty == null) { relatedToProperty = new ArrayList<>(); } return 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 index fd8d6609c2..cfbb5ac555 100644 --- 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 @@ -29,7 +29,6 @@ public final class RelationshipData { @JsonProperty("relationship-key") private String relationshipKey; - @JsonProperty("relationship-value") private String 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 index f143e01a58..5191a4449d 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import java.util.ArrayList; @@ -26,10 +25,11 @@ import lombok.Setter; @Setter public class RelationshipList { + private List relationship; public List getRelationship() { - if(relationship == null) { + if (relationship == null) { relationship = new ArrayList<>(); } return 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 3ad6728de8..c8f4b15b1c 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import java.util.List; @@ -29,6 +28,7 @@ import lombok.Setter; @Setter @AllArgsConstructor public class ServiceInfo { + private String name; private List 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 bf01436a38..ab54b47bd9 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import lombok.Getter; @@ -28,8 +27,12 @@ import lombok.Setter; @Setter @NoArgsConstructor public class ServiceVersionInfo { + private String version; private String url; + private String artifactUuid; + private String state; + private String distributionStatus; public ServiceVersionInfo(String serviceName, String serviceVersion, String context) { super(); @@ -39,12 +42,6 @@ public class ServiceVersionInfo { url = sb.toString(); } - - private String artifactUuid; - private String state; - private String distributionStatus; - - public static Builder newBuilder() { return new Builder(); } @@ -52,13 +49,17 @@ public class ServiceVersionInfo { public String getArtifactUuid() { return artifactUuid; } + public String getState() { return state; } - public String getDistributionStatus() { return distributionStatus; } + public String getDistributionStatus() { + return distributionStatus; + } public static class Builder { + private final ServiceVersionInfo instance; private Builder() { 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 1a438e57d1..3d46458dd3 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import java.util.List; @@ -27,5 +26,6 @@ import lombok.Setter; @Getter @Setter public class ServicesWrapper { + private List 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 1c0944403a..5cf827d2ed 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import lombok.Getter; @@ -26,6 +25,7 @@ import lombok.Setter; @Getter @Setter public class ServletJsonResponse { + private String source; private String description; } 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 8df81c1727..1af072e8b3 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import java.util.List; @@ -35,6 +34,7 @@ public class ToscaNodeTypeInfo { @Override public String toString() { - return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; + 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 19ed017de8..b276ec61f8 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import java.util.List; @@ -27,5 +26,6 @@ import lombok.Setter; @Getter @Setter public class ToscaNodeTypeInterface { + private List 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 7d9de792d1..76be33cedf 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 @@ -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. @@ -17,9 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.listen; +import java.io.IOException; +import java.io.InputStream; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.monitoring.BeMonitoringService; @@ -28,45 +34,28 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.listener.AppContextListener; import org.openecomp.sdc.common.log.wrappers.Logger; -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.jar.Attributes; -import java.util.jar.Manifest; - public class BEAppContextListener extends AppContextListener implements ServletContextListener { private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; private static final Logger log = Logger.getLogger(BEAppContextListener.class); public void contextInitialized(ServletContextEvent context) { - super.contextInitialized(context); - ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource()); log.debug("loading configuration from configDir: {} appName: {}", ExternalConfiguration.getConfigDir(), ExternalConfiguration.getAppName()); - context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager); - WebAppContextWrapper webAppContextWrapper = new WebAppContextWrapper(); context.getServletContext().setAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR, webAppContextWrapper); - context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context)); - // Monitoring service BeMonitoringService bms = new BeMonitoringService(context.getServletContext()); bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15)); - log.debug("After executing {}", this.getClass()); - } private String getVersionFromManifest(ServletContextEvent context) { ServletContext servletContext = context.getServletContext(); InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME); - String version = null; try { Manifest mf = new Manifest(inputStream); @@ -77,11 +66,9 @@ public class BEAppContextListener extends AppContextListener implements ServletC } 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/ComponentInstanceInputMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstanceInputMixin.java index 547ae1738d..0d2616e804 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstanceInputMixin.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstanceInputMixin.java @@ -17,26 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.view.MixinTarget; -import java.util.List; - @MixinTarget(target = ComponentInstanceInput.class) -public abstract class ComponentInstanceInputMixin extends InputDefinitionMixin{ +public abstract class ComponentInstanceInputMixin extends InputDefinitionMixin { + @JsonProperty abstract String getComponentInstanceId(); + @JsonProperty abstract String getComponentInstanceName(); + @JsonProperty abstract List getPath(); + @JsonProperty abstract List getRules(); + @JsonProperty abstract String getValueUniqueUid(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstancePropertyMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstancePropertyMixin.java index f9c41fb2d3..c5d97d6ec8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstancePropertyMixin.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstancePropertyMixin.java @@ -17,27 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.view.MixinTarget; -import java.util.List; - @MixinTarget(target = ComponentInstanceProperty.class) public abstract class ComponentInstancePropertyMixin extends PropertyDefinitionMixin { @JsonProperty abstract String getComponentInstanceId(); + @JsonProperty abstract String getComponentInstanceName(); + @JsonProperty abstract List getPath(); + @JsonProperty abstract List getRules(); + @JsonProperty abstract String getValueUniqueUid(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupCompositionMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupCompositionMixin.java index c46b064c0d..6ab0af6c89 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupCompositionMixin.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupCompositionMixin.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. @@ -17,26 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.view.Mixin; import org.openecomp.sdc.be.view.MixinTarget; -import java.util.Map; - @MixinTarget(target = GroupDataDefinition.class) -public abstract class GroupCompositionMixin extends Mixin { +public abstract class GroupCompositionMixin extends Mixin { + @JsonProperty abstract String getName(); + @JsonProperty("members") abstract Map resolveMembersList(); + @JsonProperty abstract String getUniqueId(); + @JsonProperty abstract String getType(); - - } 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 index b8ca0e30bc..db705cbf6e 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,15 +29,16 @@ public abstract class GroupTypeMixin extends Mixin { @JsonProperty abstract String getType(); + @JsonProperty abstract String getVersion(); + @JsonProperty abstract String getUniqueId(); + @JsonProperty abstract String getName(); + @JsonProperty abstract String getIcon(); - } - - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/InputDefinitionMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/InputDefinitionMixin.java index dba7ff5918..0634a57108 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/InputDefinitionMixin.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/InputDefinitionMixin.java @@ -17,22 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; 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.view.MixinTarget; -import java.util.List; - @MixinTarget(target = InputDefinition.class) public abstract class InputDefinitionMixin extends PropertyDefinitionMixin { @JsonProperty abstract List getInputs(); + @JsonProperty abstract List getProperties(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.java index 6a5d245149..a334df9ff4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.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. @@ -17,34 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.view.Mixin; import org.openecomp.sdc.be.view.MixinTarget; -import java.util.List; -import java.util.Map; - @MixinTarget(target = PolicyDataDefinition.class) -public abstract class PolicyCompositionMixin extends Mixin { +public abstract class PolicyCompositionMixin extends Mixin { + @JsonProperty abstract String getName(); + @JsonProperty abstract Map> getTargets(); + @JsonProperty abstract String getUniqueId(); + @JsonProperty("type") abstract String getPolicyTypeName(); + @JsonProperty abstract String getInputPath(); + @JsonProperty abstract String getValue(); + @JsonProperty abstract String getInstanceUniqueId(); - - } 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 index 1a371fd57a..bce79d25e6 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,15 +29,16 @@ public abstract class PolicyTypeMixin extends Mixin { @JsonProperty abstract String getName(); + @JsonProperty abstract String getType(); + @JsonProperty abstract String getVersion(); + @JsonProperty abstract String getUniqueId(); + @JsonProperty abstract String getIcon(); - } - - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PropertyDefinitionMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PropertyDefinitionMixin.java index 17dcf96113..5d567f7215 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PropertyDefinitionMixin.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PropertyDefinitionMixin.java @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import org.openecomp.sdc.be.datatypes.elements.Annotation; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; @@ -29,49 +29,66 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.view.Mixin; import org.openecomp.sdc.be.view.MixinTarget; -import java.util.List; - @MixinTarget(target = PropertyDefinition.class) public abstract class PropertyDefinitionMixin extends Mixin { @JsonProperty abstract List getAnnotations(); + @JsonProperty abstract String getDefaultValue(); + @JsonProperty abstract String getDescription(); + @JsonProperty abstract List getGetInputValues(); + @JsonProperty abstract String getInputId(); + @JsonProperty abstract String getInputPath(); + @JsonProperty abstract String getInstanceUniqueId(); + @JsonProperty abstract String getLabel(); + @JsonProperty abstract String getName(); + @JsonProperty abstract String getParentUniqueId(); + @JsonProperty abstract String getPropertyId(); + @JsonProperty abstract SchemaDefinition getSchema(); + @JsonProperty abstract SchemaDefinition getSchemaProperty(); + @JsonProperty abstract String getSchemaType(); + @JsonProperty abstract String getStatus(); + @JsonProperty abstract String getType(); + @JsonProperty abstract String getUniqueId(); + @JsonProperty abstract String getValue(); + @JsonProperty abstract boolean isGetInputProperty(); + @JsonProperty abstract List getConstraints(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/plugins/CsarEntryGenerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/plugins/CsarEntryGenerator.java index 856d53f7cd..03a2f59433 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/plugins/CsarEntryGenerator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/plugins/CsarEntryGenerator.java @@ -5,35 +5,33 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.openecomp.sdc.be.plugins; import java.util.Map; - import org.openecomp.sdc.be.model.Component; /** * Implementations of this interface shall generate entries to be included in a csar. */ public interface CsarEntryGenerator { - - /** - * Generate entries to be included in a csar. - * - * @param component the component the csar is based on - * @return Map of name to contents for entries to be included in the csar - */ - Map generateCsarEntries(final Component component); + /** + * Generate entries to be included in a csar. + * + * @param component the component the csar is based on + * @return Map of name to contents for entries to be included in the csar + */ + Map generateCsarEntries(final Component component); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/plugins/ServiceCreationPlugin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/plugins/ServiceCreationPlugin.java index 4981a33d26..f54bf49cb4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/plugins/ServiceCreationPlugin.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/plugins/ServiceCreationPlugin.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.plugins; import org.openecomp.sdc.be.model.Service; @@ -39,5 +38,4 @@ public interface ServiceCreationPlugin { * @return a order */ int getOrder(); - } 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 cb0cc239f2..beaa08cc4f 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 @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.databind.ObjectMapper; @@ -43,7 +42,6 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.collections4.MapUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -94,31 +92,38 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { private static final Logger log = Logger.getLogger(AbstractValidationsServlet.class); 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", - TOSCA_SIMPLE_YAML_PREFIX + "1_2", - TOSCA_SIMPLE_YAML_PREFIX + "1_3"); + 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", TOSCA_SIMPLE_YAML_PREFIX + "1_2", TOSCA_SIMPLE_YAML_PREFIX + "1_3"); private static final List TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(".yml", ".yaml", ".csar", ".meta"); - + protected final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; protected ServletUtils servletUtils; protected ResourceImportManager resourceImportManager; - protected final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - protected ServiceImportManager serviceImportManager; - public AbstractValidationsServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, - ServletUtils servletUtils, ResourceImportManager resourceImportManager) { + public AbstractValidationsServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) { super(userBusinessLogic, componentsUtils); this.servletUtils = servletUtils; this.resourceImportManager = resourceImportManager; this.componentInstanceBusinessLogic = componentInstanceBL; } + public static void extractZipContents(Wrapper yamlStringWrapper, File file) throws ZipException { + final Map unzippedFolder = ZipUtils.readZip(file, false); + String ymlName = unzippedFolder.keySet().iterator().next(); + fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file); + } + + private static void fillToscaTemplateFromZip(final Wrapper yamlStringWrapper, final String payloadName, final File file) + throws ZipException { + final Map unzippedFolder = ZipUtils.readZip(file, false); + final byte[] yamlFileInBytes = unzippedFolder.get(payloadName); + final String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8); + log.debug("received yaml: {}", yamlAsString); + yamlStringWrapper.setInnerElement(yamlAsString); + } + protected void init() { } @@ -126,7 +131,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { if (serviceImportManager == null) { ServletContext context = servletRequest.getSession().getServletContext(); WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context - .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); serviceImportManager = webApplicationContext.getBean(ServiceImportManager.class); } @@ -148,9 +153,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { log.info("user userId is null"); Response response = returnMissingInformation(new User()); responseWrapper.setInnerElement(response); - } - - else { + } else { UserBusinessLogic userAdmin = getServletUtils().getUserAdmin(); try { User user = userAdmin.getUser(userUserId); @@ -180,7 +183,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { break; } } - } protected void validateUserRole(Wrapper errorResponseWrapper, User user) { @@ -190,18 +192,15 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { 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(final Wrapper responseWrapper, final File zipFile, final String payloadName) { if (StringUtils.isEmpty(payloadName)) { log.info("Invalid JSON was received. Payload name is empty"); - final Response errorResponse = - buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + final Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); responseWrapper.setInnerElement(errorResponse); return; } @@ -210,19 +209,15 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { unzippedFolder = ZipUtils.readZip(zipFile, false); } catch (final ZipException e) { log.error("Could not read ZIP file '{}' for validation", zipFile.getName(), e); - final Response errorResponse = - buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + final Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); responseWrapper.setInnerElement(errorResponse); return; } if (!unzippedFolder.containsKey(payloadName)) { log.info("Could no find payload '{}' in ZIP file '{}'", payloadName, zipFile.getName()); - final Response errorResponse = - buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + final Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); responseWrapper.setInnerElement(errorResponse); } - - } protected void validateCsar(final Wrapper responseWrapper, final File csarFile, final String payloadName) { @@ -237,8 +232,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { unzippedFolder = ZipUtils.readZip(csarFile, false); } catch (final ZipException e) { log.error("Could not read CSAR file '{}' for validation", csarFile.getName(), e); - final Response errorResponse = - buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + final Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); responseWrapper.setInnerElement(errorResponse); return; } @@ -247,52 +241,29 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); responseWrapper.setInnerElement(errorResponse); } - } protected void fillZipContents(Wrapper yamlStringWrapper, File file) throws ZipException { extractZipContents(yamlStringWrapper, file); } - public static void extractZipContents(Wrapper yamlStringWrapper, File file) throws ZipException { - final Map unzippedFolder = ZipUtils.readZip(file, false); - String ymlName = unzippedFolder.keySet().iterator().next(); - fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file); - } - - private static void fillToscaTemplateFromZip(final Wrapper yamlStringWrapper, final String payloadName, - final File file) throws ZipException { - final Map unzippedFolder = ZipUtils.readZip(file, false); - final byte[] yamlFileInBytes = unzippedFolder.get(payloadName); - final 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){ + 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); + 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); - } } @@ -304,17 +275,16 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { 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) { + protected void validateAndFillResourceJson(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, User user, + ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) { boolean isValid; try { log.debug("The received json is {}", resourceInfo); @@ -330,11 +300,9 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } 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."); @@ -371,8 +339,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { log.debug("checking payload is valid tosca"); boolean isValid; Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); - Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); - + Either findFirstToscaStringElement = ImportUtils + .findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); if (findFirstToscaStringElement.isRight()) { isValid = false; } else { @@ -383,17 +351,16 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { 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) { + 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()); @@ -412,7 +379,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { * @return Resource Type name */ private String getResourceType(final String nodeTypeFullName) { - final Optional nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName); if (nodeTypeNamePrefix.isPresent()) { final String nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.get().length()); @@ -429,12 +395,13 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { /** * Extracts the Node Type Name prefix from the given Node Type Name. + * * @param nodeName - Node Type Name * @return Node Type Name prefix */ private Optional getNodeTypeNamePrefix(final String nodeName) { - final List definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager() - .getConfiguration().getDefinedResourceNamespace(); + final List definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager().getConfiguration() + .getDefinedResourceNamespace(); for (final String validNamespace : definedNodeTypeNamespaceList) { if (nodeName.startsWith(validNamespace)) { return Optional.of(validNamespace); @@ -443,13 +410,13 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { return Optional.empty(); } - protected void validatePayloadNameSpace(final Wrapper responseWrapper, - final UploadResourceInfo resourceInfo, - final User user, final String toscaPayload) { + protected void validatePayloadNameSpace(final Wrapper responseWrapper, final UploadResourceInfo resourceInfo, final User user, + final String toscaPayload) { boolean isValid; String namespace = ""; final Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); - final Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); + final Either, ResultStatusEnum> toscaElement = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); if (toscaElement.isRight() || toscaElement.left().value().size() != 1) { isValid = false; } else { @@ -466,38 +433,38 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - private void validatePayloadIsSingleResource(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { + private 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, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); + Either, ResultStatusEnum> toscaElement = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.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); } - } - private void validatePayloadIsNotService(Wrapper responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) { + private 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, TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); - + Either toscaElement = ImportUtils + .findToscaElement(mappedToscaTemplate, TypeUtils.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); } - } private void validateToscaTemplatePayloadName(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { @@ -521,7 +488,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { return isValidSuffix; } - private void validateMD5(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, String resourceInfoJsonString) { + private void validateMD5(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, + String resourceInfoJsonString) { boolean isValid; String recievedMD5 = request.getHeader(Constants.MD5_HEADER); if (recievedMD5 == null) { @@ -552,12 +520,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { throw new ByActionStatusComponentException(ActionStatus.UNSUPPORTED_ERROR, componentType); } - ComponentTypeEnum convertToComponentType(String componentType) { return validateComponentType(componentType); } - private void fillToscaTemplateFromJson(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo resourceInfo) { + private 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); @@ -568,94 +536,77 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { String decodedPayload = new String(Base64.decodeBase64(toscaPayload)); yamlStringWrapper.setInnerElement(decodedPayload); } - } - void fillPayload(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, Wrapper yamlStringWrapper, User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum, - File file) throws ZipException { - + void fillPayload(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, Wrapper yamlStringWrapper, + User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum, File file) throws ZipException { if (responseWrapper.isEmpty()) { if (resourceAuthorityEnum.isBackEndImport()) { // PrePayload Validations if (responseWrapper.isEmpty()) { validateDataNotNull(responseWrapper, file, resourceInfoJsonString); } - if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ + 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{ - + } 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(final Wrapper responseWrapper, final Wrapper uploadResourceInfoWrapper, - final Wrapper yamlStringWrapper, final User user, - final HttpServletRequest request, final String resourceInfoJsonString, - final ResourceAuthorityTypeEnum resourceAuthorityEnum) { - + final Wrapper yamlStringWrapper, final User user, final HttpServletRequest request, + final String resourceInfoJsonString, final ResourceAuthorityTypeEnum resourceAuthorityEnum) { 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()) - && responseWrapper.isEmpty()) { - validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement()); + if (resourceAuthorityEnum.isUserTypeResource() && !CsarValidationUtils + .isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName()) && responseWrapper.isEmpty()) { + validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement()); } } } - void commonGeneralValidations(Wrapper responseWrapper, Wrapper userWrapper, Wrapper uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userId, - String resourceInfoJsonString) { - + void commonGeneralValidations(Wrapper responseWrapper, Wrapper userWrapper, Wrapper uploadResourceInfoWrapper, + ResourceAuthorityTypeEnum resourceAuthorityEnum, String userId, String resourceInfoJsonString) { if (responseWrapper.isEmpty()) { validateUserExist(responseWrapper, userWrapper, userId); } - if (responseWrapper.isEmpty()) { validateUserRole(responseWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum); } - if (responseWrapper.isEmpty()) { - validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum, resourceInfoJsonString); + 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) { @@ -668,7 +619,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - private void importUIValidations(Wrapper responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, String resourceInfoJsonString) { + private void importUIValidations(Wrapper responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, + String resourceInfoJsonString) { if (responseWrapper.isEmpty()) { validateMD5(responseWrapper, user, resourceInfo, request, resourceInfoJsonString); } @@ -677,8 +629,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - void commonPayloadValidations(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { - + void commonPayloadValidations(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, + UploadResourceInfo uploadResourceInfo) { if (responseWrapper.isEmpty()) { validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); } @@ -693,8 +645,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - - void handleImport(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) { + void handleImport(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, + ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) { ImmutablePair createOrUpdateResponse = null; Response response = null; Object representation = null; @@ -707,12 +659,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true); } else { log.debug("import user resource (not normative type)"); - createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false); + createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false); } - if (createOrUpdateResponse!= null){ + if (createOrUpdateResponse != null) { importedResourceStatus = createOrUpdateResponse; } - if(importedResourceStatus != null){ + if (importedResourceStatus != null) { try { representation = RepresentationUtils.toRepresentation(importedResourceStatus.left); } catch (IOException e) { @@ -723,22 +675,22 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { responseWrapper.setInnerElement(response); } - private ImmutablePair importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) { - + private ImmutablePair importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, + String resourceUniqueId) { Resource newResource; ActionStatus actionStatus; Resource resource = new Resource(); String payloadName = resourceInfoObject.getPayloadName(); fillResourceFromResourceInfoObject(resource, resourceInfoObject); - Map csarUIPayload = getCsarFromPayload(resourceInfoObject); getAndValidateCsarYaml(csarUIPayload, resource, user, payloadName); - if (resourceUniqueId == null || resourceUniqueId.isEmpty()) { - newResource = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName); + newResource = resourceImportManager.getResourceBusinessLogic() + .createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName); actionStatus = ActionStatus.CREATED; } else { - newResource = resourceImportManager.getResourceBusinessLogic().validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId); + newResource = resourceImportManager.getResourceBusinessLogic() + .validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId); actionStatus = ActionStatus.OK; } return new ImmutablePair<>(newResource, actionStatus); @@ -753,39 +705,34 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } private void getAndValidateComponentCsarYaml(Map csarUIPayload, Component component, User user, String csarUUID) { - - Either, ResponseFormat> getToscaYamlRes = CsarValidationUtils.getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils()); - + 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); if (component instanceof Resource) { - BeEcompErrorManager.getInstance() - .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - getComponentsUtils().auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.CREATE_RESOURCE); - }else { - BeEcompErrorManager.getInstance() - .logBeDaoSystemError("Creating service from CSAR: fetching CSAR with id " + csarUUID + " failed"); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + getComponentsUtils().auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.CREATE_RESOURCE); + } else { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating service from CSAR: fetching CSAR with id " + csarUUID + " failed"); } throwComponentException(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); if (component instanceof Resource) { - getComponentsUtils().auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.IMPORT_RESOURCE); + getComponentsUtils().auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.IMPORT_RESOURCE); } throwComponentException(responseFormat); } - log.debug("checking payload is valid tosca"); Map mappedToscaTemplate = (Map) new Yaml().load(toscaYaml); - Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); - + Either findFirstToscaStringElement = ImportUtils + .findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); if (findFirstToscaStringElement.isRight()) { isValid = false; } else { @@ -796,12 +743,11 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); } } - if (!isValid) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); if (component instanceof Resource) { log.debug("enter getAndValidateComponentCsarYaml,component instanceof Resource"); - getComponentsUtils().auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.IMPORT_RESOURCE); + getComponentsUtils().auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.IMPORT_RESOURCE); } throwComponentException(responseFormat); } @@ -810,7 +756,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { private void fillResourceFromResourceInfoObject(Resource resource, UploadResourceInfo resourceInfoObject) { resourceImportManager.populateResourceMetadata(resourceInfoObject, resource); fillArtifacts(resource, resourceInfoObject); - } private void fillArtifacts(Resource resource, UploadResourceInfo resourceInfoObject) { @@ -824,7 +769,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - private void buildArtifactsHM(List artifactList, Map artifactsHM){ + private void buildArtifactsHM(List artifactList, Map artifactsHM) { for (UploadArtifactInfo artifact : artifactList) { ArtifactDefinition artifactDef = new ArtifactDefinition(); artifactDef.setArtifactName(artifact.getArtifactName()); @@ -839,22 +784,19 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { private Map getCsarFromPayload(UploadResourceInfo innerElement) { String csarUUID = innerElement.getPayloadName(); String payloadData = innerElement.getPayloadData(); - return getComponentCsarFromPayload(csarUUID, payloadData); } - private Map getComponentCsarFromPayload(String csarUUID, String payloadData){ + private Map getComponentCsarFromPayload(String csarUUID, String payloadData) { if (payloadData == null) { log.info("Failed to decode received csar {}", csarUUID); throw new ByActionStatusComponentException(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); throw new ByActionStatusComponentException(ActionStatus.CSAR_NOT_FOUND, csarUUID); } - Map csar = null; try { csar = ZipUtils.readZip(decodedPayload, false); @@ -873,7 +815,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } else { dataWrapper.setInnerElement(new String(bytes, StandardCharsets.UTF_8)); } - } void validateClassParse(String data, Wrapper parsedClassWrapper, Supplier> classGen, Wrapper errorWrapper) { @@ -890,7 +831,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper blWrapper, Wrapper errorWrapper) { + void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, + Wrapper blWrapper, Wrapper errorWrapper) { ServletContext context = request.getSession().getServletContext(); ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context); if (componentInstanceLogic == null) { @@ -915,7 +857,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper responseWrapper) { ResponseFormat responseFormat; - if(StringUtils.isEmpty(instanceIdHeader) ){ + if (StringUtils.isEmpty(instanceIdHeader)) { log.debug("Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); responseWrapper.setInnerElement(responseFormat); @@ -924,7 +866,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { protected void validateHttpCspUserIdHeader(String header, Wrapper responseWrapper) { ResponseFormat responseFormat; - if( StringUtils.isEmpty(header)){ + if (StringUtils.isEmpty(header)) { log.debug("MissingUSER_ID"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); responseWrapper.setInnerElement(responseFormat); @@ -932,7 +874,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } Either parseToObject(String json, Supplier> classSupplier) { - try { T object = RepresentationUtils.fromRepresentation(json, classSupplier.get()); return Either.left(object); @@ -953,46 +894,37 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { return Either.right(responseFormat); } } + protected void validateNotEmptyBody(String data) { if (StringUtils.isEmpty(data)) { throw new ByActionStatusComponentException(ActionStatus.MISSING_BODY); } } - protected void commonServiceGeneralValidations( - Wrapper responseWrapper, Wrapper userWrapper, - Wrapper uploadServiceInfoWrapper, ServiceAuthorityTypeEnum serviceAuthorityEnum, - String userUserId, - String serviceInfoJsonString) { - + protected void commonServiceGeneralValidations(Wrapper responseWrapper, Wrapper userWrapper, + Wrapper uploadServiceInfoWrapper, ServiceAuthorityTypeEnum serviceAuthorityEnum, + String userUserId, String serviceInfoJsonString) { if (responseWrapper.isEmpty()) { validateUserExist(responseWrapper, userWrapper, userUserId); } - if (responseWrapper.isEmpty()) { validateUserRole(responseWrapper, userWrapper.getInnerElement(), serviceAuthorityEnum); } - if (responseWrapper.isEmpty()) { - validateAndFillServiceJson(responseWrapper, uploadServiceInfoWrapper, userWrapper.getInnerElement(), - serviceAuthorityEnum, serviceInfoJsonString); + validateAndFillServiceJson(responseWrapper, uploadServiceInfoWrapper, userWrapper.getInnerElement(), serviceAuthorityEnum, + serviceInfoJsonString); } - if (responseWrapper.isEmpty()) { - validateToscaTemplatePayloadName(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), - userWrapper.getInnerElement()); + validateToscaTemplatePayloadName(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), userWrapper.getInnerElement()); } - } - protected void validateUserRole(Wrapper errorResponseWrapper, User user, - ServiceAuthorityTypeEnum serviceAuthority) { + protected void validateUserRole(Wrapper errorResponseWrapper, User user, ServiceAuthorityTypeEnum serviceAuthority) { log.debug("validate user role"); if (serviceAuthority == ServiceAuthorityTypeEnum.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); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); log.debug("audit before sending response"); Response response = buildErrorResponse(responseFormat); errorResponseWrapper.setInnerElement(response); @@ -1000,12 +932,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } else { validateUserRole(errorResponseWrapper, user); } - } - protected void validateAndFillServiceJson(Wrapper responseWrapper, - Wrapper uploadServiceInfoWrapper, User user, - ServiceAuthorityTypeEnum serviceAuthorityEnum, String serviceInfo) { + protected void validateAndFillServiceJson(Wrapper responseWrapper, Wrapper uploadServiceInfoWrapper, User user, + ServiceAuthorityTypeEnum serviceAuthorityEnum, String serviceInfo) { boolean isValid; try { log.debug("The received json is {}", serviceInfo); @@ -1014,25 +944,19 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { isValid = false; } else { if (!serviceAuthorityEnum.isBackEndImport()) { - isValid = - serviceInfoObject.getPayloadName() != null && !serviceInfoObject.getPayloadName().isEmpty(); + isValid = serviceInfoObject.getPayloadName() != null && !serviceInfoObject.getPayloadName().isEmpty(); //only service name is checked } else { isValid = true; } uploadServiceInfoWrapper.setInnerElement(serviceInfoObject); - log.debug("get isValid:{},serviceInfoObject get name:{},get tags:{},getContactId:{}," + - " getPayloadName:{}",isValid, - uploadServiceInfoWrapper.getInnerElement().getName(), - uploadServiceInfoWrapper.getInnerElement().getTags(), - uploadServiceInfoWrapper.getInnerElement().getContactId(), - uploadServiceInfoWrapper.getInnerElement().getPayloadName()); + log.debug("get isValid:{},serviceInfoObject get name:{},get tags:{},getContactId:{}," + " getPayloadName:{}", isValid, + uploadServiceInfoWrapper.getInnerElement().getName(), uploadServiceInfoWrapper.getInnerElement().getTags(), + uploadServiceInfoWrapper.getInnerElement().getContactId(), uploadServiceInfoWrapper.getInnerElement().getPayloadName()); } - } catch (JsonSyntaxException e) { log.debug("enter validateAndFillServiceJson,Invalid json was received. {}", e.getMessage(), e); isValid = false; - } if (!isValid) { log.info("Invalid json was received."); @@ -1042,72 +966,60 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - protected void validateToscaTemplatePayloadName(Wrapper responseWrapper, - UploadServiceInfo uploadServiceInfo, User user) { + protected void validateToscaTemplatePayloadName(Wrapper responseWrapper, UploadServiceInfo uploadServiceInfo, User user) { String toscaTemplatePayloadName = uploadServiceInfo.getPayloadName(); boolean isValidSuffix = isToscaTemplatePayloadNameValid(responseWrapper, toscaTemplatePayloadName); if (!isValidSuffix) { - ResponseFormat responseFormat = - getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION); Response errorResponse = buildErrorResponse(responseFormat); responseWrapper.setInnerElement(errorResponse); } - } - - protected void specificServiceAuthorityValidations(Wrapper responseWrapper, - Wrapper uploadServiceInfoWrapper, Wrapper yamlStringWrapper, User user, - HttpServletRequest request, String serviceInfoJsonString, ServiceAuthorityTypeEnum serviceAuthorityEnum) + protected void specificServiceAuthorityValidations(Wrapper responseWrapper, Wrapper uploadServiceInfoWrapper, + Wrapper yamlStringWrapper, User user, HttpServletRequest request, + String serviceInfoJsonString, ServiceAuthorityTypeEnum serviceAuthorityEnum) throws FileNotFoundException { - if (responseWrapper.isEmpty()) { // UI Only Validation if (!serviceAuthorityEnum.isBackEndImport()) { - importUIValidations(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), user, request, - serviceInfoJsonString); + importUIValidations(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), user, request, serviceInfoJsonString); } - // User Defined Type Services - if (serviceAuthorityEnum.isUserTypeService() && !CsarValidationUtils.isCsarPayloadName( - uploadServiceInfoWrapper.getInnerElement().getPayloadName())) { + if (serviceAuthorityEnum.isUserTypeService() && !CsarValidationUtils + .isCsarPayloadName(uploadServiceInfoWrapper.getInnerElement().getPayloadName())) { if (responseWrapper.isEmpty()) { - validatePayloadNameSpace(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), user, - yamlStringWrapper.getInnerElement()); + validatePayloadNameSpace(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement()); } - } } } - protected void importUIValidations(Wrapper responseWrapper, UploadServiceInfo serviceInfo, User user, - HttpServletRequest request, String serviceInfoJsonString) { + protected void importUIValidations(Wrapper responseWrapper, UploadServiceInfo serviceInfo, User user, HttpServletRequest request, + String serviceInfoJsonString) { if (responseWrapper.isEmpty()) { validateMD5(responseWrapper, user, serviceInfo, request, serviceInfoJsonString); } - if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod() - .equals("POST")) { + if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod().equals("POST")) { validateServiceDoesNotExist(responseWrapper, user, serviceInfo.getName()); } } - protected void validatePayloadNameSpace(Wrapper responseWrapper, UploadServiceInfo serviceInfo, User user, - String toscaPayload) { + protected void validatePayloadNameSpace(Wrapper responseWrapper, UploadServiceInfo serviceInfo, User user, String toscaPayload) { boolean isValid; String nameSpace = ""; Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); - Either, ResultStatusEnum> toscaElement = - ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); + Either, ResultStatusEnum> toscaElement = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.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_SERVICE_NAMESPACE_PREFIX); - log.debug("enter validatePayloadNameSpace,get nameSpace:{},get Valid is:{}",nameSpace,isValid); + log.debug("enter validatePayloadNameSpace,get nameSpace:{},get Valid is:{}", nameSpace, isValid); } if (!isValid) { - ResponseFormat responseFormat = - getComponentsUtils().getResponseFormat(ActionStatus.INVALID_SERVICE_NAMESPACE); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_SERVICE_NAMESPACE); Response errorResponse = buildErrorResponse(responseFormat); responseWrapper.setInnerElement(errorResponse); } else { @@ -1120,11 +1032,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { serviceInfo.setServiceType(ResourceTypeEnum.SERVICE.name()); } } - } - protected void validateMD5(Wrapper responseWrapper, User user, UploadServiceInfo serviceInfo, - HttpServletRequest request, String serviceInfoJsonString) { + protected void validateMD5(Wrapper responseWrapper, User user, UploadServiceInfo serviceInfo, HttpServletRequest request, + String serviceInfoJsonString) { boolean isValid; String recievedMD5 = request.getHeader(Constants.MD5_HEADER); if (recievedMD5 == null) { @@ -1134,14 +1045,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { isValid = calculateMD5.equals(recievedMD5); } if (!isValid) { - ResponseFormat responseFormat = - getComponentsUtils().getResponseFormat(ActionStatus.INVALID_SERVICE_CHECKSUM); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_SERVICE_CHECKSUM); Response errorResponse = buildErrorResponse(responseFormat); responseWrapper.setInnerElement(errorResponse); } } - protected void validateServiceDoesNotExist(Wrapper responseWrapper, User user, String serviceName) { if (serviceImportManager.isServiceExist(serviceName)) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.SERVICE_ALREADY_EXISTS); @@ -1150,10 +1059,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } - protected void handleImportService(Wrapper responseWrapper, User user, - UploadServiceInfo serviceInfoObject, String yamlAsString, ServiceAuthorityTypeEnum authority, - boolean createNewVersion, String serviceUniqueId) throws ZipException { - + protected void handleImportService(Wrapper responseWrapper, User user, UploadServiceInfo serviceInfoObject, String yamlAsString, + ServiceAuthorityTypeEnum authority, boolean createNewVersion, String serviceUniqueId) throws ZipException { Response response = null; Object representation = null; ImmutablePair importedServiceStatus = null; @@ -1161,57 +1068,45 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { log.debug("import service from csar"); importedServiceStatus = importServiceFromUICsar(serviceInfoObject, user, serviceUniqueId); } - if (importedServiceStatus != null) { try { representation = RepresentationUtils.toRepresentation(importedServiceStatus.left); } catch (IOException e) { log.debug("Error while building service representation : {}", e.getMessage(), e); } - response = buildOkResponse(getComponentsUtils().getResponseFormat(importedServiceStatus.right), - representation); + response = buildOkResponse(getComponentsUtils().getResponseFormat(importedServiceStatus.right), representation); } responseWrapper.setInnerElement(response); } - private ImmutablePair importServiceFromUICsar(UploadServiceInfo serviceInfoObject, User user, - String serviceUniqueId) throws ZipException { - + private ImmutablePair importServiceFromUICsar(UploadServiceInfo serviceInfoObject, User user, String serviceUniqueId) + throws ZipException { Service newService; ImmutablePair result = null; ActionStatus actionStatus; Service service = new Service(); String payloadName = serviceInfoObject.getPayloadName(); fillServiceFromServiceInfoObject(service, serviceInfoObject); - Map csarUIPayloadRes = getCsarFromPayload(serviceInfoObject); - getAndValidateCsarYaml(csarUIPayloadRes, service, user, payloadName); - newService = serviceImportManager.getServiceImportBusinessLogic() - .createService(service, AuditingActionEnum.CREATE_SERVICE, user, csarUIPayloadRes, - payloadName); + .createService(service, AuditingActionEnum.CREATE_SERVICE, user, csarUIPayloadRes, payloadName); actionStatus = ActionStatus.CREATED; - return new ImmutablePair<>(newService, actionStatus); } - private void fillServiceFromServiceInfoObject(Service service, UploadServiceInfo serviceInfoObject) { serviceImportManager.populateServiceMetadata(serviceInfoObject, service); fillArtifacts(service, serviceInfoObject); - } - private Map getCsarFromPayload(UploadServiceInfo innerElement) - throws ZipException { + private Map getCsarFromPayload(UploadServiceInfo innerElement) throws ZipException { String csarUUID = innerElement.getPayloadName(); String payloadData = innerElement.getPayloadData(); return getComponentCsarFromPayload(csarUUID, payloadData); } - private void getAndValidateCsarYaml(Map csarUIPayload, Service service, User user, - String csarUUID) { + private void getAndValidateCsarYaml(Map csarUIPayload, Service service, User user, String csarUUID) { getAndValidateComponentCsarYaml(csarUIPayload, service, user, csarUUID); } @@ -1225,8 +1120,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } } } + /** * import service payload to postman + * * @param responseWrapper * @param uploadServiceInfoWrapper * @param yamlStringWrapper @@ -1236,8 +1133,9 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { * @param file * @throws ZipException */ - protected void fillServicePayload(Wrapper responseWrapper, Wrapper uploadServiceInfoWrapper, Wrapper yamlStringWrapper, User user, String serviceInfoJsonString, ServiceAuthorityTypeEnum serviceAuthorityEnum, - File file) throws ZipException { + protected void fillServicePayload(Wrapper responseWrapper, Wrapper uploadServiceInfoWrapper, + Wrapper yamlStringWrapper, User user, String serviceInfoJsonString, + ServiceAuthorityTypeEnum serviceAuthorityEnum, File file) throws ZipException { log.debug("enter fillServicePayload"); if (responseWrapper.isEmpty()) { log.debug("enter fillServicePayload,get responseWrapper is empty"); @@ -1246,20 +1144,18 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { if (responseWrapper.isEmpty()) { validateDataNotNull(responseWrapper, file, serviceInfoJsonString); } - if (responseWrapper.isEmpty()){ + if (responseWrapper.isEmpty()) { log.debug("enter fillServicePayload,responseWrapper is empty"); } - if(!serviceAuthorityEnum.equals(ServiceAuthorityTypeEnum.CSAR_TYPE_BE)){ + if (!serviceAuthorityEnum.equals(ServiceAuthorityTypeEnum.CSAR_TYPE_BE)) { if (responseWrapper.isEmpty()) { validateZip(responseWrapper, file, uploadServiceInfoWrapper.getInnerElement().getPayloadName()); } - // Fill PayLoad From File if (responseWrapper.isEmpty()) { fillToscaTemplateFromZip(yamlStringWrapper, uploadServiceInfoWrapper.getInnerElement().getPayloadName(), file); } - }else{ - + } else { log.debug("enter fillServicePayload,ServiceAuthorityTypeEnum is CSAR_TYPE_BE"); if (responseWrapper.isEmpty()) { validateCsar(responseWrapper, file, uploadServiceInfoWrapper.getInnerElement().getPayloadName()); @@ -1271,50 +1167,41 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { if (responseWrapper.isEmpty()) { fillServicePayloadDataFromFile(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), file); } - } - } else { // Fill PayLoad From JSON if (responseWrapper.isEmpty()) { fillServiceToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadServiceInfoWrapper.getInnerElement()); } } - } - } - protected void fillServicePayloadDataFromFile(Wrapper responseWrapper, UploadServiceInfo uploadServiceInfoWrapper, File file) { - try(InputStream fileInputStream = new FileInputStream(file)){ - + protected void fillServicePayloadDataFromFile(Wrapper responseWrapper, UploadServiceInfo uploadServiceInfoWrapper, File file) { + try (InputStream fileInputStream = new FileInputStream(file)) { log.debug("enter fillServicePayloadDataFromFile"); - byte [] data = new byte[(int)file.length()]; - if( fileInputStream.read(data) == -1){ + 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); + String payloadData = Base64.encodeBase64String(data); uploadServiceInfoWrapper.setPayloadData(payloadData); - log.debug("enter fillServicePayloadDataFromFile,get payloadData:{}", - uploadServiceInfoWrapper.getPayloadData()); - - log.debug("enter fillServicePayloadDataFromFile,get uploadService:{}",uploadServiceInfoWrapper); - + log.debug("enter fillServicePayloadDataFromFile,get payloadData:{}", uploadServiceInfoWrapper.getPayloadData()); + log.debug("enter fillServicePayloadDataFromFile,get uploadService:{}", uploadServiceInfoWrapper); } 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); } } - private void fillServiceToscaTemplateFromJson(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadServiceInfo serviceInfo) { + private void fillServiceToscaTemplateFromJson(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, + UploadServiceInfo serviceInfo) { if (serviceInfo.getPayloadData() == null || serviceInfo.getPayloadData().isEmpty()) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD); Response errorResponse = buildErrorResponse(responseFormat); @@ -1326,5 +1213,4 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { yamlStringWrapper.setInnerElement(decodedPayload); } } - } 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 574d200382..d9e5aed187 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -32,21 +31,6 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic; -import org.openecomp.sdc.be.components.impl.aaf.AafPermission; -import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.exception.ResponseFormat; -import org.springframework.stereotype.Controller; - import javax.inject.Inject; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -62,7 +46,20 @@ 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.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic; +import org.openecomp.sdc.be.components.impl.aaf.AafPermission; +import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.AdditionalInformationDefinition; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Controller; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @@ -75,19 +72,16 @@ public class AdditionalInformationServlet extends BeGenericServlet { private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; private static final String MODIFIER_ID_IS = "modifier id is {}"; private static final String FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY = "Failed to update additional information property. Reason - {}"; - private final AdditionalInformationBusinessLogic businessLogic; @Inject - public AdditionalInformationServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - AdditionalInformationBusinessLogic businessLogic) { + public AdditionalInformationServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + AdditionalInformationBusinessLogic businessLogic) { super(userBusinessLogic, componentsUtils); this.businessLogic = businessLogic; } /** - * * @param resourceId * @param data * @param request @@ -98,28 +92,21 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/resources/{resourceId}/additionalinfo") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Additional Information Label and Value", method = "POST", - summary = "Returns created Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Additional information created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Create Additional Information Label and Value", method = "POST", summary = "Returns created Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Additional information created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createResourceAdditionalInformationLabel( - @Parameter(description = "resource id to update with new property", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "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); - + @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "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 @@ -130,27 +117,21 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/services/{serviceId}/additionalinfo") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Additional Information Label and Value", method = "POST", - summary = "Returns created Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Additional information created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Create Additional Information Label and Value", method = "POST", summary = "Returns created Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Additional information created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createServiceAdditionalInformationLabel( - @Parameter(description = "service id to update with new property", - required = true) @PathParam("serviceId") final String serviceId, - @Parameter(description = "Additional information key value to be created", required = true) String data, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { - + @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "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 @@ -162,28 +143,22 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/resources/{resourceId}/additionalinfo/{labelId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Additional Information Label and Value", method = "PUT", - summary = "Returns updated Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Additional information updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Update Additional Information Label and Value", method = "PUT", summary = "Returns updated Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Additional information updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateResourceAdditionalInformationLabel( - @Parameter(description = "resource id to update with new property", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, - @Parameter(description = "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); - + @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, + @Parameter(description = "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 @@ -195,28 +170,22 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/services/{serviceId}/additionalinfo/{labelId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Additional Information Label and Value", method = "PUT", - summary = "Returns updated Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Additional information updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Update Additional Information Label and Value", method = "PUT", summary = "Returns updated Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Additional information updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateServiceAdditionalInformationLabel( - @Parameter(description = "service id to update with new property", - required = true) @PathParam("serviceId") final String serviceId, - @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, - @Parameter(description = "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); - + @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, + @Parameter(description = "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 @@ -227,27 +196,21 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/resources/{resourceId}/additionalinfo/{labelId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Additional Information Label and Value", method = "DELETE", - summary = "Returns deleted Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Additional information deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Create Additional Information Label and Value", method = "DELETE", summary = "Returns deleted Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Additional information deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateResourceAdditionalInformationLabel( - @Parameter(description = "resource id to update with new property", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "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); - + @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "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 @@ -258,26 +221,21 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/services/{serviceId}/additionalinfo/{labelId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Additional Information Label and Value", method = "DELETE", - summary = "Returns deleted Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Additional information deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Create Additional Information Label and Value", method = "DELETE", summary = "Returns deleted Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Additional information deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deleteServiceAdditionalInformationLabel( - @Parameter(description = "service id to update with new property", - required = true) @PathParam("serviceId") final String serviceId, - @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "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 @@ -288,26 +246,21 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/resources/{resourceId}/additionalinfo/{labelId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Additional Information by id", method = "GET", - summary = "Returns Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "fetched additional information"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Get Additional Information by id", method = "GET", summary = "Returns Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "fetched additional information"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getResourceAdditionalInformationLabel( - @Parameter(description = "resource id to update with new property", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "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 @@ -318,26 +271,21 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/services/{serviceId}/additionalinfo/{labelId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Additional Information by id", method = "GET", - summary = "Returns Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "fetched additional information"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Get Additional Information by id", method = "GET", summary = "Returns Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "fetched additional information"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getServiceAdditionalInformationLabel( - @Parameter(description = "service id to update with new property", - required = true) @PathParam("serviceId") final String serviceId, - @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "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 @@ -347,25 +295,20 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/resources/{resourceId}/additionalinfo") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get all Additional Information under resource", method = "GET", - summary = "Returns Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "list of additional information"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Get all Additional Information under resource", method = "GET", summary = "Returns Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "list of additional information"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getAllResourceAdditionalInformationLabel( - @Parameter(description = "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) { - + @Parameter(description = "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 @@ -375,25 +318,20 @@ public class AdditionalInformationServlet extends BeGenericServlet { @Path("/services/{serviceId}/additionalinfo") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get all Additional Information under service", method = "GET", - summary = "Returns Additional Inforamtion property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "list of additional information"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) + @Operation(description = "Get all Additional Information under service", method = "GET", summary = "Returns Additional Inforamtion property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "list of additional information"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Additional information key already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getAllServiceAdditionalInformationLabel( - @Parameter(description = "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) { - + @Parameter(description = "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 @@ -403,42 +341,34 @@ public class AdditionalInformationServlet extends BeGenericServlet { * @param data * @return */ - protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) { - + 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 - - Either either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId); - + Either either = businessLogic + .createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, 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()); - + 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); } - } /** @@ -452,49 +382,39 @@ public class AdditionalInformationServlet extends BeGenericServlet { * @param data * @return */ - protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) { - + 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 - additionalInfoParameterInfo.setUniqueId(labelId); - - Either either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId); - + Either either = businessLogic + .updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId); if (either.isRight()) { ResponseFormat responseFormat = either.right().value(); log.info(FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY, responseFormat); return buildErrorResponse(responseFormat); } - AdditionalInfoParameterInfo createdAI = either.left().value(); - - log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - + log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), + createdAI.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); return buildOkResponse(responseFormat, createdAI); - } 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 @@ -504,41 +424,33 @@ public class AdditionalInformationServlet extends BeGenericServlet { * @param userId * @return */ - protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { - + protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, + HttpServletRequest request, 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 { - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); additionalInfoParameterInfo.setUniqueId(labelId); - - Either either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId); - + Either either = businessLogic + .deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId); if (either.isRight()) { ResponseFormat responseFormat = either.right().value(); log.info(FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY, responseFormat); return buildErrorResponse(responseFormat); } - 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); - } 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); } - } /** @@ -551,45 +463,34 @@ public class AdditionalInformationServlet extends BeGenericServlet { * @param userId * @return */ - protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { - + protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, + 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 { - // create the new property - - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); additionalInfoParameterInfo.setUniqueId(labelId); - - Either either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId); - + Either either = businessLogic + .getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId); if (either.isRight()) { ResponseFormat responseFormat = either.right().value(); log.info(FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY, responseFormat); return buildErrorResponse(responseFormat); } - 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); - } 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); } - } /** @@ -601,39 +502,28 @@ public class AdditionalInformationServlet extends BeGenericServlet { * @param userId * @return */ - protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) { - + protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, + 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 { - - - Either either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, userId); if (either.isRight()) { ResponseFormat responseFormat = either.right().value(); log.info(FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY, responseFormat); return buildErrorResponse(responseFormat); } - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); return buildOkResponse(responseFormat, additionalInformationDefinition); - } 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); } - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArchiveEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArchiveEndpoint.java index 1ab30b115c..f2930615be 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArchiveEndpoint.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArchiveEndpoint.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -30,6 +29,20 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import javax.inject.Inject; +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.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdc.be.components.impl.ArchiveBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; @@ -44,22 +57,6 @@ import org.openecomp.sdc.common.log.enums.StatusCode; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; -import javax.inject.Inject; -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.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Tags({@Tag(name = "SDC Internal APIs")}) @@ -67,148 +64,132 @@ import java.util.Map; @Controller @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -public class ArchiveEndpoint extends BeGenericServlet{ +public class ArchiveEndpoint extends BeGenericServlet { private static final String COMPONENT_ID = "Component ID= "; - private final ArchiveBusinessLogic archiveBusinessLogic; private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ArchiveEndpoint.class.getName()); + private final ArchiveBusinessLogic archiveBusinessLogic; @Inject - public ArchiveEndpoint(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, ArchiveBusinessLogic archiveBusinessLogic) { + public ArchiveEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, ArchiveBusinessLogic archiveBusinessLogic) { super(userBusinessLogic, componentsUtils); this.archiveBusinessLogic = archiveBusinessLogic; } @POST @Path("/resources/{componentId}/archive") - @Operation(description = "Archive Resource", method = "POST", - summary = "Marks a resource as archived. Can be restored with restore action", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "Archive successful"), - @ApiResponse(responseCode = "400", description = "Bad request"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @Operation(description = "Archive Resource", method = "POST", summary = "Marks a resource as archived. Can be restored with restore action", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "Archive successful"), @ApiResponse(responseCode = "400", description = "Bad request"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response archiveResources(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE,StatusCode.STARTED,"Archive Resource " + COMPONENT_ID + " " + componentId + " by "+ userId); + public Response archiveResources(@PathParam("componentId") final String componentId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + loggerSupportability + .log(LoggerSupportabilityActions.ARCHIVE, StatusCode.STARTED, "Archive Resource " + COMPONENT_ID + " " + componentId + " by " + userId); archiveBusinessLogic.archiveComponent(ComponentTypeEnum.RESOURCE_PARAM_NAME, userId, componentId); - loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE,StatusCode.COMPLETE,"Archive Resource " + COMPONENT_ID + " " + componentId + " by "+ userId); + loggerSupportability + .log(LoggerSupportabilityActions.ARCHIVE, StatusCode.COMPLETE, "Archive Resource " + COMPONENT_ID + " " + componentId + " by " + userId); return Response.ok().build(); } @POST @Path("/resources/{componentId}/restore") - @Operation(description = "Restore Resource", method = "POST", summary = "Restores a resource from archive.", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "Restore successful"), - @ApiResponse(responseCode = "400", description = "Bad request"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @Operation(description = "Restore Resource", method = "POST", summary = "Restores a resource from archive.", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "Restore successful"), @ApiResponse(responseCode = "400", description = "Bad request"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response restoreResource(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE,StatusCode.STARTED,"Restore resource from archive " + COMPONENT_ID + " " + componentId + " by "+ userId); + public Response restoreResource(@PathParam("componentId") final String componentId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE, StatusCode.STARTED, + "Restore resource from archive " + COMPONENT_ID + " " + componentId + " by " + userId); archiveBusinessLogic.restoreComponent(ComponentTypeEnum.RESOURCE_PARAM_NAME, userId, componentId); - loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE,StatusCode.COMPLETE,"Restore resource from archive " + COMPONENT_ID + " " + componentId + " by "+ userId); + loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE, StatusCode.COMPLETE, + "Restore resource from archive " + COMPONENT_ID + " " + componentId + " by " + userId); return Response.ok().build(); } @POST @Path("/services/{componentId}/archive") - @Operation(description = "Archive Service", method = "POST", - summary = "Marks a service as archived. Can be restored with restore action", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "Archive successful"), - @ApiResponse(responseCode = "400", description = "Bad request"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @Operation(description = "Archive Service", method = "POST", summary = "Marks a service as archived. Can be restored with restore action", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "Archive successful"), @ApiResponse(responseCode = "400", description = "Bad request"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response archiveService(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE, StatusCode.STARTED, "Archive Service for " + COMPONENT_ID + " " + componentId + " by " + userId); + loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE, StatusCode.STARTED, + "Archive Service for " + COMPONENT_ID + " " + componentId + " by " + userId); archiveBusinessLogic.archiveComponent(ComponentTypeEnum.SERVICE_PARAM_NAME, userId, componentId); - loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE,StatusCode.COMPLETE, "Archive Service for " + COMPONENT_ID + " " + componentId + " by " + userId); + loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE, StatusCode.COMPLETE, + "Archive Service for " + COMPONENT_ID + " " + componentId + " by " + userId); return Response.ok().build(); } - @POST @Path("/services/{componentId}/restore") - @Operation(description = "Restore Service", method = "POST", summary = "Restores a service from archive.", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "Restore successful"), - @ApiResponse(responseCode = "400", description = "Bad request"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @Operation(description = "Restore Service", method = "POST", summary = "Restores a service from archive.", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "Restore successful"), @ApiResponse(responseCode = "400", description = "Bad request"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response restoreService(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE,StatusCode.STARTED,"Restore service from archive " + COMPONENT_ID + " " + componentId + " by "+ userId); + loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE, StatusCode.STARTED, + "Restore service from archive " + COMPONENT_ID + " " + componentId + " by " + userId); archiveBusinessLogic.restoreComponent(ComponentTypeEnum.SERVICE_PARAM_NAME, userId, componentId); - loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE,StatusCode.COMPLETE,"Restore service from archive " + COMPONENT_ID + " " + componentId + " by "+ userId); + loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE, StatusCode.COMPLETE, + "Restore service from archive " + COMPONENT_ID + " " + componentId + " by " + userId); return Response.ok().build(); } @GET @Path("/archive") - @Operation(description = "Get all Archived Components", method = "GET", summary = "Get all Archived Components", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "400", description = "Bad request"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @Operation(description = "Get all Archived Components", method = "GET", summary = "Get all Archived Components", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "400", description = "Bad request"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Map> getArchivedComponents(@HeaderParam(value = Constants.USER_ID_HEADER) String userId){ + public Map> getArchivedComponents(@HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return this.archiveBusinessLogic.getArchiveComponents(userId, new LinkedList<>()); } @POST @Path("/notif/vsp/archived") - @Operation( - description = "Notify about an archived VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=true", - method = "POST", responses = {@ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "400", description = "Bad request"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "500", - description = "Internal Error. A list of the failed CSAR IDs may be returned.")}) + @Operation(description = "Notify about an archived VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=true", method = "POST", responses = { + @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "400", description = "Bad request"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "500", description = "Internal Error. A list of the failed CSAR IDs may be returned.")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response onVspArchived(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List csarIds){ + public Response onVspArchived(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List csarIds) { List failedCsarIds = this.archiveBusinessLogic.onVspArchive(userId, csarIds); - if (!failedCsarIds.isEmpty()){ + if (!failedCsarIds.isEmpty()) { //There are some failed CSAR IDs, return 500 and the list of failed CSAR IDs Map> entity = new HashMap<>(); entity.put("failedIds", failedCsarIds); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(entity) - .build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(entity).build(); } return Response.ok().build(); } @POST @Path("/notif/vsp/restored") - @Operation( - description = "Notify about a restored VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=false", - method = "POST", responses = {@ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "400", description = "Bad request"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "500", - description = "Internal Error. A list of the failed CSAR IDs may be returned.")}) + @Operation(description = "Notify about a restored VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=false", method = "POST", responses = { + @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "400", description = "Bad request"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "500", description = "Internal Error. A list of the failed CSAR IDs may be returned.")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response onVspRestored(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List csarIds){ + public Response onVspRestored(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List csarIds) { List failedCsarIds = this.archiveBusinessLogic.onVspRestore(userId, csarIds); - if (!failedCsarIds.isEmpty()){ + if (!failedCsarIds.isEmpty()) { //There are some failed CSAR IDs, return 500 and the list of failed CSAR IDs Map> entity = new HashMap<>(); entity.put("failedIds", failedCsarIds); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(entity) - .build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(entity).build(); } return Response.ok().build(); } - } 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 037ca47b13..93f9fff931 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -32,6 +31,20 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.Map; +import javax.inject.Inject; +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 org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; @@ -55,21 +68,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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) */ @@ -80,42 +78,37 @@ import java.util.Map; @Controller public class ArtifactServlet extends BeGenericServlet { + private static final Logger log = Logger.getLogger(ArtifactServlet.class); + private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ArtifactServlet.class.getName()); + private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; + private static final String DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64 = "downloadResourceInstanceArtifactBase64"; + private static final String DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64_EXCEPTION = "downloadResourceInstanceArtifactBase64 unexpected exception"; private final ArtifactsBusinessLogic artifactsBusinessLogic; @Inject - public ArtifactServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, ArtifactsBusinessLogic artifactsBusinessLogic) { + public ArtifactServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, ArtifactsBusinessLogic artifactsBusinessLogic) { super(userBusinessLogic, componentsUtils); this.artifactsBusinessLogic = artifactsBusinessLogic; } - private static final Logger log = Logger.getLogger(ArtifactServlet.class); - private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ArtifactServlet.class.getName()); - - private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; - private static final String DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64 = "downloadResourceInstanceArtifactBase64"; - private static final String DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64_EXCEPTION = "downloadResourceInstanceArtifactBase64 unexpected exception"; - // *************** Resources @POST @Path("/resources/{resourceId}/artifacts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Artifact already exist")}) + @Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Artifact already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response loadArtifact(@PathParam("resourceId") final String resourceId, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + @Parameter(description = "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); - return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE); + return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE); } @POST @@ -123,16 +116,14 @@ public class ArtifactServlet extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Update Artifact", method = "POST", summary = "Returns updated artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateArtifact(@PathParam("resourceId") final String resourceId, - @PathParam("artifactId") final String artifactId, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, + @Parameter(description = "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 { @@ -149,14 +140,13 @@ public class ArtifactServlet extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Delete Artifact", method = "DELETE", summary = "Returns delete artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteArtifact(@PathParam("resourceId") final String resourceId, - @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - + 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 { @@ -172,18 +162,16 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/services/{serviceId}/artifacts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Artifact already exist")}) + @Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Artifact already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + @Parameter(description = "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 { @@ -200,15 +188,13 @@ public class ArtifactServlet extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Update Artifact", method = "POST", summary = "Returns updated artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Service artifact created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) - public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, - @PathParam("artifactId") final String artifactId, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Service artifact created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, + @Parameter(description = "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 { @@ -225,19 +211,16 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/services/{serviceId}/artifacts/api/{artifactId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Api Artifact", method = "POST", summary = "Returns created ArtifactDefinition", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Api Artifact Updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Api Artifact", method = "POST", summary = "Returns created ArtifactDefinition", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Api Artifact Updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, - @PathParam("artifactId") final String artifactId, - @Parameter(description = "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) { - + public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, + @Parameter(description = "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 { @@ -253,17 +236,14 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/services/{serviceId}/artifacts/api/{artifactId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete Api Artifact", method = "DELETE", summary = "Returns Deleted ArtifactDefinition", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "204", description = "Api Artifact deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation")}) + @Operation(description = "Delete Api Artifact", method = "DELETE", summary = "Returns Deleted ArtifactDefinition", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "204", description = "Api Artifact deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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) { - + 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 { @@ -280,14 +260,13 @@ public class ArtifactServlet extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Delete Artifact", method = "DELETE", summary = "Returns delete artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Service artifact deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Service artifact deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, - @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - + 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 { @@ -302,32 +281,28 @@ public class ArtifactServlet extends BeGenericServlet { /* * 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) - @Operation(description = "Download service Artifact in Base64", method = "GET", - summary = "Returns downloaded artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Service artifact downloaded"), - @ApiResponse(responseCode = "404", description = "Service/Artifact not found")}) + @Operation(description = "Download service Artifact in Base64", method = "GET", summary = "Returns downloaded artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Service artifact downloaded"), + @ApiResponse(responseCode = "404", description = "Service/Artifact not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, - @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - + public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, + @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); Response response; log.debug(START_HANDLE_REQUEST_OF, url); try { - response = handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null); + response = handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64"); log.debug("downloadServiceArtifactBase64 unexpected exception", e); throw e; - } - finally { - loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS,StatusCode.COMPLETE,"Ended download Service Artifact "); + } finally { + loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.COMPLETE, "Ended download Service Artifact "); } return response; } @@ -336,14 +311,12 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/resources/{resourceId}/artifacts/{artifactId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Download resource Artifact in Base64", method = "GET", - summary = "Returns downloaded artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource artifact downloaded"), - @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")}) - public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, - @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - + @Operation(description = "Download resource Artifact in Base64", method = "GET", summary = "Returns downloaded artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource artifact downloaded"), + @ApiResponse(responseCode = "404", description = "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); Response response; @@ -353,10 +326,9 @@ public class ArtifactServlet extends BeGenericServlet { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64"); log.debug("downloadResourceArtifactBase64 unexpected exception", e); throw e; - } - finally { - loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS,null, StatusCode.COMPLETE,"Ended download artifact {}", artifactId); - + } finally { + loggerSupportability + .log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, null, StatusCode.COMPLETE, "Ended download artifact {}", artifactId); } return response; } @@ -365,86 +337,79 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Download component Artifact in Base64", method = "GET", - summary = "Returns downloaded artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "ResourceInstance artifact downloaded"), - @ApiResponse(responseCode = "404", description = "ResourceInstance/Artifact not found")}) + @Operation(description = "Download component Artifact in Base64", method = "GET", summary = "Returns downloaded artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "ResourceInstance artifact downloaded"), + @ApiResponse(responseCode = "404", description = "ResourceInstance/Artifact not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response downloadResourceInstanceArtifactBase64(@Parameter( - description = "valid values: resources / services", - schema = @Schema(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) { - + public Response downloadResourceInstanceArtifactBase64( + @Parameter(description = "valid values: resources / services", schema = @Schema(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) { Response response; String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.STARTED," Starting to download Resource Instance Artifact for component {} ", componentId); + loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.STARTED, + " Starting to download Resource Instance Artifact for component {} ", componentId); try { - response = handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType); + response = handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, + containerComponentType); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64); log.debug(DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64_EXCEPTION, e); throw e; - } - finally { - loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.COMPLETE,"Ended download Resource Instance Artifact for component {} ", componentId); + } finally { + loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.COMPLETE, + "Ended download Resource Instance Artifact for component {} ", componentId); } return response; } // *************** Resource lifecycle ( interfces ) - @POST @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Artifact and Attach to interface", method = "POST", - summary = "Returns created resource", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Artifact already exist")}) + @Operation(description = "Create Artifact and Attach to interface", method = "POST", summary = "Returns created resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Artifact already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + 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, + @Parameter(description = "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, false); + return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, + ArtifactOperationEnum.CREATE, null, null, false); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface"); log.debug("loadArtifactToInterface unexpected exception", e); throw e; } - } @DELETE @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "delete Artifact from interface", method = "delete", - summary = "delete matching artifact from interface", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Artifact already exist")}) + @Operation(description = "delete Artifact from interface", method = "delete", summary = "delete matching artifact from interface", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Artifact already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { - + @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 { @@ -460,25 +425,24 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "update Artifact Attach to interface", method = "post", - summary = "updates artifact by interface", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Artifact already exist")}) + @Operation(description = "update Artifact Attach to interface", method = "post", summary = "updates artifact by interface", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Artifact already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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, - @Parameter(description = "json describe the artifact", required = true) String data) { - + @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, + @Parameter(description = "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, false); + return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, + ArtifactOperationEnum.UPDATE, null, null, false); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface"); log.debug("updateArtifactToInterface unexpected exception", e); @@ -490,35 +454,31 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Resource Instance HEAT_ENV parameters", method = "POST", - summary = "Returns updated artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Artifact updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Resource Instance HEAT_ENV parameters", method = "POST", summary = "Returns updated artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Artifact updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateRIArtifact(@Parameter(description = "valid values: resources / services", - schema = @Schema(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, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + public Response updateRIArtifact( + @Parameter(description = "valid values: resources / services", schema = @Schema(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, @Parameter(description = "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); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_HEAT, StatusCode.STARTED,"Starting update RI Artifact {}" ,artifactId); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_HEAT, StatusCode.STARTED, "Starting update RI Artifact {}", artifactId); Response response; try { - response = handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType, false); + response = handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, + ArtifactOperationEnum.UPDATE, componentId, containerComponentType, false); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact"); log.debug("updateRIArtifact unexpected exception", e); throw e; - } - finally { - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_HEAT, StatusCode.COMPLETE,"Ending update RI Artifact {}" , artifactId); + } finally { + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_HEAT, StatusCode.COMPLETE, "Ending update RI Artifact {}", artifactId); } return response; } @@ -527,28 +487,27 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Resource Instance artifact payload", method = "POST", - summary = "Returns updated artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Artifact updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Resource Instance artifact payload", method = "POST", summary = "Returns updated artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Artifact updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @Parameter(description = "valid values: resources / services", - schema = @Schema(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, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @Parameter(description = "valid values: resources / services", schema = @Schema(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, + @Parameter(description = "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, true); + return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, + ArtifactOperationEnum.UPDATE, componentId, containerComponentType, true); } catch (Exception e) { log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); throw e; @@ -559,27 +518,26 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Load Resource Instance artifact payload", method = "POST", - summary = "Returns updated artifact", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Artifact updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Load Resource Instance artifact payload", method = "POST", summary = "Returns updated artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Artifact updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME , - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, - @PathParam("componentInstanceId") final String componentInstanceId, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("componentInstanceId") final String componentInstanceId, + @Parameter(description = "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, false); + return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, + ArtifactOperationEnum.CREATE, componentId, containerComponentType, false); } catch (Exception e) { log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); throw e; @@ -590,57 +548,53 @@ public class ArtifactServlet extends BeGenericServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete Resource Instance artifact", method = "POST", summary = "Returns deleted artifact", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Artifact updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Delete Resource Instance artifact", method = "POST", summary = "Returns deleted artifact", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Artifact updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @Parameter(description = "valid values: resources / services", - schema = @Schema(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, - @Parameter(description = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - + @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @Parameter(description = "valid values: resources / services", schema = @Schema(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, + @Parameter(description = "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); - loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE_ARTIFACT,null, StatusCode.STARTED,"Starting delete component instance artifact {}" ,artifactId); + loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE_ARTIFACT, null, StatusCode.STARTED, + "Starting delete component instance artifact {}", artifactId); Response response; try { response = handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId); } catch (Exception e) { log.debug("deleteArtifact unexpected exception", e); throw e; - } - finally { - loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE_ARTIFACT,null, StatusCode.COMPLETE,"Ending delete component instance artifact {}" ,artifactId); + } finally { + loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE_ARTIFACT, null, StatusCode.COMPLETE, + "Ending delete component instance artifact {}", artifactId); } return response; - } - @GET @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Get component Artifacts", method = "GET", summary = "Returns artifacts", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Component artifacts"), - @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Component artifacts"), + @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getComponentArtifacts(@Parameter(description = "valid values: resources / services", - schema = @Schema(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) { - + public Response getComponentArtifacts( + @Parameter(description = "valid values: resources / services", schema = @Schema(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 { @@ -657,17 +611,15 @@ public class ArtifactServlet extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Get component Artifacts", method = "GET", summary = "Returns artifacts", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Component artifacts"), - @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Component artifacts"), + @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getComponentInstanceArtifacts(@Parameter(description = "valid values: resources / services", - schema = @Schema(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) { - + public Response getComponentInstanceArtifacts( + @Parameter(description = "valid values: resources / services", schema = @Schema(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 { @@ -679,76 +631,64 @@ public class ArtifactServlet extends BeGenericServlet { } } - @POST @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "uploads of artifact to component operation workflow", method = "POST", - summary = "uploads of artifact to component operation workflow", responses = { - @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), - @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), - @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(responseCode = "400", - description = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(responseCode = "400", - description = "Artifact name given in input already exists in the context of the asset - SVC4125"), - @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), - @ApiResponse(responseCode = "400", - description = "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(responseCode = "400", - description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - public Response uploadInterfaceOperationArtifact( - @Parameter(description = "Asset type") @PathParam("assetType") String assetType, - @Parameter(description = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @Parameter(description = "The uuid of the interface", required = true)@PathParam("interfaceUUID") final String interfaceUUID, - @Parameter(description = "The uuid of the operation", required = true)@PathParam("operationUUID") final String operationUUID, - @Parameter(description = "The uuid of the artifact", required = true)@PathParam("artifactUUID") final String artifactUUID, - @Parameter( hidden = true) String data, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @Context final HttpServletRequest request) { - + @Operation(description = "uploads of artifact to component operation workflow", method = "POST", summary = "uploads of artifact to component operation workflow", responses = { + @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))), + @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"), + @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"), + @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"), + @ApiResponse(responseCode = "400", description = "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(responseCode = "400", description = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + public Response uploadInterfaceOperationArtifact(@Parameter(description = "Asset type") @PathParam("assetType") String assetType, + @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid, + @Parameter(description = "The uuid of the interface", required = true) @PathParam("interfaceUUID") final String interfaceUUID, + @Parameter(description = "The uuid of the operation", required = true) @PathParam("operationUUID") final String operationUUID, + @Parameter(description = "The uuid of the artifact", required = true) @PathParam("artifactUUID") final String artifactUUID, + @Parameter(hidden = true) String data, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - + log.debug("Start handle request of {}", url); try { - Either uploadArtifactEither = - artifactsBusinessLogic.updateArtifactOnInterfaceOperationByResourceUUID(data, request, - ComponentTypeEnum.findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID, - new ResourceCommonInfo(assetType), new ArtifactOperationInfo(true, - false, ArtifactOperationEnum.UPDATE)); + Either uploadArtifactEither = artifactsBusinessLogic + .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum.findByParamName(assetType), uuid, interfaceUUID, + operationUUID, artifactUUID, new ResourceCommonInfo(assetType), + new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); if (uploadArtifactEither.isRight()) { log.debug("failed to update artifact"); return buildErrorResponse(uploadArtifactEither.right().value()); } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uploadArtifactEither.left().value()); - } - catch (Exception e) { + } catch (Exception e) { final String message = "failed to update artifact on a resource or service"; BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); log.debug(message, 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, componentId, null, componentType, ArtifactOperationEnum.CREATE); } - private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) { + private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, + ComponentTypeEnum componentType) { return handleArtifactRequest(data, componentId, artifactId, componentType, ArtifactOperationEnum.UPDATE); } - private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) { + private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, + ComponentTypeEnum componentType, String containerComponentType) { String userId = request.getHeader(Constants.USER_ID_HEADER); - ImmutablePair actionResult = artifactsBusinessLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType); - + ImmutablePair actionResult = artifactsBusinessLogic + .handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType); Response response; byte[] file = actionResult.getRight(); String base64Contents = new String(Base64.encodeBase64(file)); @@ -761,25 +701,28 @@ public class ArtifactServlet extends BeGenericServlet { return response; } - private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) { + private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, + String containerComponentType) { String userId = request.getHeader(Constants.USER_ID_HEADER); - ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty() ? ComponentTypeEnum.findByParamName(containerComponentType) : ComponentTypeEnum.RESOURCE_INSTANCE; - Map actionResult = artifactsBusinessLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId); - + ComponentTypeEnum componentTypeEnum = + parentId == null || parentId.isEmpty() ? ComponentTypeEnum.findByParamName(containerComponentType) : ComponentTypeEnum.RESOURCE_INSTANCE; + Map actionResult = artifactsBusinessLogic + .handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult); } - - private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) { + 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) { + 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); - Either actionResult = artifactsBusinessLogic.handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), artifactId, null, null, null, interfaceType, operationName, - parentId, null); + Either actionResult = artifactsBusinessLogic + .handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), + artifactId, null, null, null, interfaceType, operationName, parentId, null); Response response; - Either result = actionResult; if (result.isLeft()) { response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); @@ -787,34 +730,32 @@ public class ArtifactServlet extends BeGenericServlet { 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, + private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, + String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId, String containerComponentType, boolean validateTimeout) { - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_ARTIFACT, StatusCode.STARTED,"Starting to update artifact {} " ,artifactId + " for component " + componentId); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_ARTIFACT, StatusCode.STARTED, "Starting to update artifact {} ", + artifactId + " for component " + componentId); ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, validateTimeout); String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either result = artifactsBusinessLogic.handleArtifactRequest(componentId, userId, componentType, - new ArtifactOperationInfo(false, false, operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId, - containerComponentType); + Either result = artifactsBusinessLogic + .handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, operationEnum), artifactId, + artifactInfo, origMd5, data, interfaceName, operationName, parentId, containerComponentType); Response response; if (result.isLeft()) { response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); } else { response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); } - - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_ARTIFACT, StatusCode.COMPLETE,"Ended update artifact {} " ,artifactId + " for component " + componentId); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_ARTIFACT, StatusCode.COMPLETE, "Ended update artifact {} ", + artifactId + " for component " + componentId); return response; - } - private Response handleArtifactRequest(String data, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) { + private Response handleArtifactRequest(String data, String componentId, String artifactId, ComponentTypeEnum componentType, + ArtifactOperationEnum operation) { return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null, false); } - } 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 227627304a..c9af80624a 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 @@ -17,12 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.jcabi.aspects.Loggable; import fj.data.Either; import io.swagger.v3.oas.annotations.Operation; @@ -55,7 +52,6 @@ import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.model.AttributeDefinition; @@ -84,10 +80,8 @@ public class AttributeServlet extends AbstractValidationsServlet { private static final String ATTRIBUTE_CONTENT_IS_INVALID = "Attribute content is invalid - {}"; @Inject - public AttributeServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager) { + public AttributeServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, + ServletUtils servletUtils, ResourceImportManager resourceImportManager) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); } @@ -104,8 +98,7 @@ public class AttributeServlet extends AbstractValidationsServlet { @Path("resources/{resourceId}/attributes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Resource Attribute", method = "POST", - summary = "Returns created resource attribute", responses = { + @Operation(description = "Create Resource Attribute", method = "POST", summary = "Returns created resource attribute", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), @ApiResponse(responseCode = "201", description = "Resource property created"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @@ -113,32 +106,25 @@ public class AttributeServlet extends AbstractValidationsServlet { @ApiResponse(responseCode = "409", description = "Resource attribute already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createAttribute( - @Parameter(description = "resource id to update with new attribute", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "Resource attribute to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) - throws IOException { - + @Parameter(description = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "Resource attribute to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { 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 { final Wrapper errorWrapper = new Wrapper<>(); AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper); - if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either createAttribute = businessLogic. - createAttribute(resourceId, attributeDataDefinition, userId); + Either createAttribute = businessLogic + .createAttribute(resourceId, attributeDataDefinition, userId); if (createAttribute.isRight()) { errorWrapper.setInnerElement(createAttribute.right().value()); } else { attributeDataDefinition = createAttribute.left().value(); } } - if (!errorWrapper.isEmpty()) { log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); return buildErrorResponse(errorWrapper.getInnerElement()); @@ -147,7 +133,6 @@ public class AttributeServlet extends AbstractValidationsServlet { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition)); } - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute"); log.debug("create property failed with exception", e); @@ -169,46 +154,37 @@ public class AttributeServlet extends AbstractValidationsServlet { @Path("resources/{resourceId}/attributes/{attributeId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource attribute updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource attribute updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateAttribute( - @Parameter(description = "resource id to update with new attribute", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "attribute id to update", - required = true) @PathParam("attributeId") final String attributeId, - @Parameter(description = "Resource attribute to update", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) - throws IOException { - + @Parameter(description = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, + @Parameter(description = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { 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 { final Wrapper errorWrapper = new Wrapper<>(); AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherUpdateAttribute - = businessLogic.updateAttribute(resourceId, attributeId, attributeDataDefinition, userId); + Either eitherUpdateAttribute = businessLogic + .updateAttribute(resourceId, attributeId, attributeDataDefinition, userId); if (eitherUpdateAttribute.isRight()) { errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); } else { attributeDataDefinition = eitherUpdateAttribute.left().value(); } } - if (!errorWrapper.isEmpty()) { log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); return buildErrorResponse(errorWrapper.getInnerElement()); @@ -217,7 +193,6 @@ public class AttributeServlet extends AbstractValidationsServlet { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition)); } - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute"); log.debug("update attribute failed with exception", e); @@ -238,45 +213,34 @@ public class AttributeServlet extends AbstractValidationsServlet { @Path("resources/{resourceId}/attributes/{attributeId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "204", description = "deleted attribute"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Resource property not found")}) + @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "204", description = "deleted attribute"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Resource property not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deleteAttribute( - @Parameter(description = "resource id of attribute", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "Attribute id to delete", - required = true) @PathParam("attributeId") final String attributeId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) - throws IOException { - + @Parameter(description = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { 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); + 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()); } AttributeDefinition 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); @@ -284,9 +248,7 @@ public class AttributeServlet extends AbstractValidationsServlet { } } - private AttributeDefinition convertJsonToObject(final String data, - final Wrapper errorWrapper) { - + private AttributeDefinition convertJsonToObject(final String data, final Wrapper errorWrapper) { final ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(data, AttributeDefinition.class); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpoint.java index 3602003815..8a16c43e10 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpoint.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpoint.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,19 +30,7 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdc.be.components.impl.aaf.AafPermission; -import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; -import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic; -import org.openecomp.sdc.be.components.upgrade.UpgradeRequest; -import org.openecomp.sdc.be.components.upgrade.UpgradeStatus; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Controller; - +import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; @@ -56,7 +43,18 @@ 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; +import org.openecomp.sdc.be.components.impl.aaf.AafPermission; +import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; +import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic; +import org.openecomp.sdc.be.components.upgrade.UpgradeRequest; +import org.openecomp.sdc.be.components.upgrade.UpgradeStatus; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Controller; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @@ -66,14 +64,12 @@ import java.util.List; @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class AutomatedUpgradeEndpoint extends BeGenericServlet { - private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class); + private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class); private final UpgradeBusinessLogic businessLogic; @Inject - public AutomatedUpgradeEndpoint(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - UpgradeBusinessLogic businessLogic) { + public AutomatedUpgradeEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, UpgradeBusinessLogic businessLogic) { super(userBusinessLogic, componentsUtils); this.businessLogic = businessLogic; } @@ -83,57 +79,45 @@ public class AutomatedUpgradeEndpoint extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Autometed upgrade", method = "POST", summary = "....", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response autometedUpgrade(@PathParam("componentType") final String componentType, - @Context final HttpServletRequest request, @PathParam("componentId") final String componentId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "json describes upgrade request", required = true) String data) { - - + public Response autometedUpgrade(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, + @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "json describes upgrade request", required = true) String data) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(POST) Start handle request of {}", url); - try { - List inputsToUpdate = JsonParserUtils.toList(data, UpgradeRequest.class); - if (log.isDebugEnabled()) { log.debug("Received upgrade requests size is {}", inputsToUpdate == null ? 0 : inputsToUpdate.size()); } UpgradeStatus actionResponse = businessLogic.automatedUpgrade(componentId, inputsToUpdate, userId); - return actionResponse.getStatus() == ActionStatus.OK ? buildOkResponse(actionResponse) : buildErrorResponse(actionResponse.getError()); - } catch (Exception e) { log.error("#autometedUpgrade - Exception occurred during autometed Upgrade", e); throw e; } } - + @GET @Path("/{componentType}/{componentId}/dependencies") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Autometed upgrade", method = "POST", summary = "....", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getComponentDependencies(@PathParam("componentType") final String componentType, - @Context final HttpServletRequest request, @PathParam("componentId") final String componentId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "Consumer Object to be created", required = true) List data) { + public Response getComponentDependencies(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, + @PathParam("componentId") final String componentId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "Consumer Object to be created", required = true) List data) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(GET) Start handle request of {}", url); - try { - return businessLogic.getComponentDependencies(componentId, userId) - .either(this::buildOkResponse, this::buildErrorResponse); + return businessLogic.getComponentDependencies(componentId, userId).either(this::buildOkResponse, this::buildErrorResponse); } catch (Exception e) { log.error("#getServicesForComponent - Exception occurred during autometed Upgrade", e); throw e; 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 ffaf8a8399..43f51664b5 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -31,6 +30,21 @@ import fj.data.Either; import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.servers.Server; +import java.io.IOException; +import java.lang.reflect.Type; +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.Set; +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.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @@ -55,9 +69,9 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer; @@ -70,46 +84,28 @@ import org.openecomp.sdc.common.servlets.BasicServlet; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.web.context.WebApplicationContext; -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.io.IOException; -import java.lang.reflect.Type; -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.Set; -import java.util.function.Supplier; - -@OpenAPIDefinition(info = @Info(title = "SDC API", description = "SDC External, Distribution and Internal APIs"), - servers = {@Server(url = "/sdc", description = "SDC External and Distribution APIs"), - @Server(url = "/sdc2/rest", description = "SDC Internal APIs")}) +@OpenAPIDefinition(info = @Info(title = "SDC API", description = "SDC External, Distribution and Internal APIs"), servers = { + @Server(url = "/sdc", description = "SDC External and Distribution APIs"), @Server(url = "/sdc2/rest", description = "SDC Internal APIs")}) public class BeGenericServlet extends BasicServlet { - public BeGenericServlet(UserBusinessLogic userAdminManager, - ComponentsUtils componentsUtils) { - this.userAdminManager = userAdminManager; - this.componentsUtils = componentsUtils; - } - + private static final Logger log = Logger.getLogger(BeGenericServlet.class); + private static final String PROPERTY_NAME_REGEX = "[\\w,\\d,_]+"; @Context protected HttpServletRequest servletRequest; + protected ComponentsUtils componentsUtils; + private UserBusinessLogic userAdminManager; - private static final Logger log = Logger.getLogger(BeGenericServlet.class); - - private static final String PROPERTY_NAME_REGEX = "[\\w,\\d,_]+"; + public BeGenericServlet(UserBusinessLogic userAdminManager, ComponentsUtils componentsUtils) { + this.userAdminManager = userAdminManager; + this.componentsUtils = componentsUtils; + } - private UserBusinessLogic userAdminManager; - protected ComponentsUtils componentsUtils; + private static Response buildOkResponseStatic(Object entity) { + return Response.status(Response.Status.OK).entity(entity).build(); + } /******************** New error response mechanism * @param requestErrorWrapper **************/ - protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); } @@ -122,18 +118,14 @@ public class BeGenericServlet extends BasicServlet { return buildOkResponseStatic(entity); } - private static Response buildOkResponseStatic(Object entity) { - return Response.status(Response.Status.OK) - .entity(entity) - .build(); - } - public HttpServletRequest getServletRequest() { return servletRequest; } @VisibleForTesting - public void setRequestServlet(HttpServletRequest request) {this.servletRequest = request;} + public void setRequestServlet(HttpServletRequest request) { + this.servletRequest = request; + } protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) { return buildOkResponse(errorResponseWrapper, entity, null); @@ -143,16 +135,18 @@ public class BeGenericServlet extends BasicServlet { int status = errorResponseWrapper.getStatus(); ResponseBuilder responseBuilder = Response.status(status); if (entity != null) { - if (log.isTraceEnabled()) + 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()) + if (log.isTraceEnabled()) { log.trace("Adding header {} with value {} to the response", headerName, headerValue); + } responseBuilder.header(headerName, headerValue); } } @@ -212,8 +206,7 @@ public class BeGenericServlet extends BasicServlet { } /** - * Used to support Unit Test.
- * Header Params are not supported in Unit Tests + * Used to support Unit Test.
Header Params are not supported in Unit Tests * * @return */ @@ -233,16 +226,13 @@ public class BeGenericServlet extends BasicServlet { T convertJsonToObjectOfClass(String json, Class clazz) { T object = null; - ObjectMapper mapper = new ObjectMapper() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + 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) { return object; @@ -264,28 +254,21 @@ public class BeGenericServlet extends BasicServlet { 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(); - - if(!isPropertyNameValid(propertyName)) { + if (!isPropertyNameValid(propertyName)) { return Either.right(ActionStatus.INVALID_PROPERTY_NAME); } - JSONObject value = (JSONObject) next.getValue(); - Either propertyDefinitionEither = - getPropertyDefinitionFromJson(componentId, propertyName, value); - - if(propertyDefinitionEither.isRight()) { + Either propertyDefinitionEither = getPropertyDefinitionFromJson(componentId, propertyName, value); + if (propertyDefinitionEither.isRight()) { return Either.right(propertyDefinitionEither.right().value()); } - properties.put(propertyName, propertyDefinitionEither.left().value()); } - return Either.left(properties); } catch (ParseException e) { log.info("Property conetnt is invalid - {}", data); @@ -294,9 +277,7 @@ public class BeGenericServlet extends BasicServlet { } protected boolean isPropertyNameValid(String propertyName) { - return Objects.nonNull(propertyName) - && propertyName.matches(PROPERTY_NAME_REGEX); - + return Objects.nonNull(propertyName) && propertyName.matches(PROPERTY_NAME_REGEX); } private Either getPropertyDefinitionFromJson(String componentId, String propertyName, JSONObject value) { @@ -308,7 +289,6 @@ public class BeGenericServlet extends BasicServlet { PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName); propertyDefinition.setUniqueId(uniqueId); - return Either.left(propertyDefinition); } @@ -321,36 +301,29 @@ public class BeGenericServlet extends BasicServlet { InputDefinition inputDefinition = convertJsonToObject.left().value(); String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, inputName); inputDefinition.setUniqueId(uniqueId); - return Either.left(inputDefinition); } protected Either, ActionStatus> getPropertiesListForUpdate(String data) { - Map properties = new HashMap<>(); JSONParser parser = new JSONParser(); JSONArray jsonArray; - try { jsonArray = (JSONArray) parser.parse(data); for (Object jsonElement : jsonArray) { String propertyAsString = jsonElement.toString(); Either convertJsonToObject = convertJsonToObject(propertyAsString, PropertyDefinition.class); - if (convertJsonToObject.isRight()) { return Either.right(convertJsonToObject.right().value()); } - PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); properties.put(propertyDefinition.getName(), propertyDefinition); } - return Either.left(properties); } catch (Exception e) { log.info("Property content is invalid - {}", data); return Either.right(ActionStatus.INVALID_CONTENT); } - } protected String propertyToJson(Map.Entry property) { @@ -364,27 +337,24 @@ public class BeGenericServlet extends BasicServlet { } private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) { - Either either = convertObjectToJson(propertyDefinition); if (either.isRight()) { return new JSONObject(); } try { - return (JSONObject) new JSONParser().parse(either.left().value()); + return (JSONObject) new JSONParser().parse(either.left().value()); } catch (ParseException e) { log.info("failed to convert input to json"); log.error("failed to convert to json", e); return new JSONObject(); } - } - protected Either convertJsonToObject(String data, Class clazz) { + protected Either convertJsonToObject(String data, Class clazz) { T t = null; Type constraintType = new TypeToken() { }.getType(); - Gson - gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintDeserialiser()).create(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintDeserialiser()).create(); try { log.trace("convert json to object. json=\n {}", data); t = gson.fromJson(data, clazz); @@ -419,7 +389,6 @@ public class BeGenericServlet extends BasicServlet { log.debug("failed to convert fto json", e); return Either.right(ActionStatus.INVALID_CONTENT); } - } private OutputsBusinessLogic getOutputBL(final ServletContext context) { @@ -438,46 +407,38 @@ public class BeGenericServlet extends BasicServlet { return ((WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).getWebAppContext(context); } - protected Either parseToComponentInstanceMap(final String componentJson, - final User user, - final ComponentTypeEnum componentType, - final Class clazz) { + protected Either parseToComponentInstanceMap(final String componentJson, final User user, + final ComponentTypeEnum componentType, final Class clazz) { return getComponentsUtils() .convertJsonToObjectUsingObjectMapper(componentJson, user, clazz, AuditingActionEnum.CREATE_RESOURCE, componentType); } - protected Response declareProperties(String userId, String componentId, String componentType, - String componentInstInputsMapObj, DeclarationTypeEnum typeEnum, HttpServletRequest request) { + protected Response declareProperties(String userId, String componentId, String componentType, String componentInstInputsMapObj, + DeclarationTypeEnum typeEnum, HttpServletRequest request) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of {}", url); - try { BaseBusinessLogic businessLogic = getBlForDeclaration(typeEnum, context); - // get modifier id User modifier = new User(); modifier.setUserId(userId); log.debug("modifier id is {}", userId); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - Either componentInstInputsMapRes = parseToComponentInstanceMap( - componentInstInputsMapObj, modifier, componentTypeEnum, ComponentInstInputsMap.class); + Either componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, + modifier, componentTypeEnum, ComponentInstInputsMap.class); if (componentInstInputsMapRes.isRight()) { log.debug("failed to parse componentInstInputsMap"); return buildErrorResponse(componentInstInputsMapRes.right().value()); } - Either, ResponseFormat> propertiesAfterDeclaration = businessLogic - .declareProperties(userId, componentId, - componentTypeEnum, - componentInstInputsMapRes.left().value()); + .declareProperties(userId, componentId, componentTypeEnum, componentInstInputsMapRes.left().value()); if (propertiesAfterDeclaration.isRight()) { log.debug("failed to create inputs for service: {}", componentId); return buildErrorResponse(propertiesAfterDeclaration.right().value()); } Object properties = RepresentationUtils.toRepresentation(propertiesAfterDeclaration.left().value()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId); log.debug("Properties declaration failed with exception", e); @@ -485,8 +446,7 @@ public class BeGenericServlet extends BasicServlet { } } - public BaseBusinessLogic getBlForDeclaration(final DeclarationTypeEnum typeEnum, - final ServletContext context) { + public BaseBusinessLogic getBlForDeclaration(final DeclarationTypeEnum typeEnum, final ServletContext context) { switch (typeEnum) { case OUTPUT: return getOutputBL(context); @@ -505,28 +465,21 @@ public class BeGenericServlet extends BasicServlet { try { Map inputs = new HashMap<>(); root = (JSONObject) parser.parse(data); - Set entrySet = root.entrySet(); Iterator iterator = entrySet.iterator(); while (iterator.hasNext()) { Entry next = (Entry) iterator.next(); String inputName = (String) next.getKey(); - - if(!isInputNameValid(inputName)) { + if (!isInputNameValid(inputName)) { return Either.right(ActionStatus.INVALID_INPUT_NAME); } - JSONObject value = (JSONObject) next.getValue(); - Either inputDefinitionEither = - getInputDefinitionFromJson(componentId, inputName, value); - - if(inputDefinitionEither.isRight()) { + Either inputDefinitionEither = getInputDefinitionFromJson(componentId, inputName, value); + if (inputDefinitionEither.isRight()) { return Either.right(inputDefinitionEither.right().value()); } - inputs.put(inputName, inputDefinitionEither.left().value()); } - return Either.left(inputs); } catch (ParseException e) { log.warn("Input content is invalid - {}", data, e); @@ -535,8 +488,6 @@ public class BeGenericServlet extends BasicServlet { } protected boolean isInputNameValid(String inputName) { - return Objects.nonNull(inputName) - && inputName.matches(PROPERTY_NAME_REGEX); - + return Objects.nonNull(inputName) && inputName.matches(PROPERTY_NAME_REGEX); } } 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 fb32038d6e..afb037fee0 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.google.gson.Gson; @@ -30,6 +29,17 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; +import javax.inject.Inject; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +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 javax.ws.rs.core.Response; import org.apache.commons.lang3.tuple.Pair; import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -42,18 +52,6 @@ import org.openecomp.sdc.common.api.HealthCheckWrapper; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -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 javax.ws.rs.core.Response; -import java.util.List; - @Loggable(prepend = true, value = Loggable.TRACE, trim = false) @Path("/") @Tag(name = "SDC Internal APIs") @@ -61,15 +59,13 @@ import java.util.List; @Controller public class BeMonitoringServlet extends BeGenericServlet { - private final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - private static final Logger log = Logger.getLogger(BeMonitoringServlet.class); + private final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); private final HealthCheckBusinessLogic healthCheckBusinessLogic; @Inject - public BeMonitoringServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - HealthCheckBusinessLogic healthCheckBusinessLogic){ + public BeMonitoringServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + HealthCheckBusinessLogic healthCheckBusinessLogic) { super(userBusinessLogic, componentsUtils); this.healthCheckBusinessLogic = healthCheckBusinessLogic; } @@ -78,11 +74,10 @@ public class BeMonitoringServlet extends BeGenericServlet { @Path("/healthCheck") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Return aggregate BE health check of SDC BE components", - summary = "return BE health check", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "SDC BE components are all up"), - @ApiResponse(responseCode = "500", description = "One or more SDC BE components are down")}) + @Operation(description = "Return aggregate BE health check of SDC BE components", summary = "return BE health check", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "SDC BE components are all up"), + @ApiResponse(responseCode = "500", description = "One or more SDC BE components are down")}) public Response getHealthCheck(@Context final HttpServletRequest request) { try { Pair> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus(); @@ -95,11 +90,10 @@ public class BeMonitoringServlet extends BeGenericServlet { 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 + // 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); @@ -111,5 +105,4 @@ public class BeMonitoringServlet extends BeGenericServlet { ServletContext servletContext = request.getSession().getServletContext(); return (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CapabilityServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CapabilityServlet.java index a7f2230eed..3470d9f92b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CapabilityServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CapabilityServlet.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -28,6 +27,23 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.List; +import java.util.Optional; +import javax.inject.Inject; +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.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; @@ -48,24 +64,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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; -import java.util.Optional; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Consumes(MediaType.APPLICATION_JSON) @@ -74,78 +72,65 @@ import java.util.Optional; @Servers({@Server(url = "/sdc2/rest")}) @Controller public class CapabilityServlet extends AbstractValidationsServlet { + private static final Logger LOGGER = Logger.getLogger(CapabilityServlet.class); private final CapabilitiesBusinessLogic capabilitiesBusinessLogic; @Inject - public CapabilityServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - CapabilitiesBusinessLogic capabilitiesBusinessLogic) { + public CapabilityServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, + ServletUtils servletUtils, ResourceImportManager resourceImportManager, + CapabilitiesBusinessLogic capabilitiesBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.capabilitiesBusinessLogic = capabilitiesBusinessLogic; } - @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/capabilities") - @Operation(description = "Create Capabilities on resource", method = "POST", - summary = "Create Capabilities on resource", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Create Capabilities"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Capability already exist")}) + @Operation(description = "Create Capabilities on resource", method = "POST", summary = "Create Capabilities on resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Create Capabilities"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Capability already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createCapabilitiesOnResource( - @Parameter(description = "Capability to create", required = true) String data, - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, "resources" , resourceId, - request, userId, false, "createCapabilities"); + public Response createCapabilitiesOnResource(@Parameter(description = "Capability to create", required = true) String data, + @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, "resources", resourceId, request, userId, false, "createCapabilities"); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/capabilities") - @Operation(description = "Update Capabilities on resource", method = "PUT", - summary = "Update Capabilities on resource", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Update Capabilities"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Capabilities on resource", method = "PUT", summary = "Update Capabilities on resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Update Capabilities"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateCapabilitiesOnResource( - @Parameter(description = "Capabilities to update", required = true) String data, - @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, "resources", resourceId, - request, userId, true, "updateCapabilities"); + public Response updateCapabilitiesOnResource(@Parameter(description = "Capabilities to update", required = true) String data, + @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, "resources", resourceId, request, userId, true, "updateCapabilities"); } @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/capabilities/{capabilityId}") - @Operation(description = "Get Capability from resource", method = "GET", summary = "GET Capability from resource", - responses = {@ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), - @ApiResponse(responseCode = "201", description = "GET Capability"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Get Capability from resource", method = "GET", summary = "GET Capability from resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), + @ApiResponse(responseCode = "201", description = "GET Capability"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getCapabilityOnResource( - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response getCapabilityOnResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return get(capabilityId, resourceId, request, userId); } @@ -153,18 +138,16 @@ public class CapabilityServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/capabilities/{capabilityId}") - @Operation(description = "Delete capability from resource", method = "DELETE", - summary = "Delete capability from resource", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Delete capability"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Delete capability from resource", method = "DELETE", summary = "Delete capability from resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Delete capability"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteCapabilityOnResource( - @Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId, - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response deleteCapabilityOnResource(@Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId, + @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return delete(capabilityId, resourceId, request, userId); } @@ -172,60 +155,49 @@ public class CapabilityServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/capabilities") - @Operation(description = "Create Capabilities on service", method = "POST", - summary = "Create Capabilities on service", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Create Capabilities"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Capability already exist")}) + @Operation(description = "Create Capabilities on service", method = "POST", summary = "Create Capabilities on service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Create Capabilities"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Capability already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createCapabilitiesOnService( - @Parameter(description = "Capability to create", required = true) String data, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, "services" , serviceId, - request, userId, false, "createCapabilities"); + public Response createCapabilitiesOnService(@Parameter(description = "Capability to create", required = true) String data, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, "services", serviceId, request, userId, false, "createCapabilities"); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/capabilities") - @Operation(description = "Update Capabilities on service", method = "PUT", - summary = "Update Capabilities on service", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Update Capabilities"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Capabilities on service", method = "PUT", summary = "Update Capabilities on service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Update Capabilities"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateCapabilitiesOnService( - @Parameter(description = "Capabilities to update", required = true) String data, - @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, "services", serviceId, - request, userId, true, "updateCapabilities"); + public Response updateCapabilitiesOnService(@Parameter(description = "Capabilities to update", required = true) String data, + @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, "services", serviceId, request, userId, true, "updateCapabilities"); } @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/capabilities/{capabilityId}") - @Operation(description = "Get Capability from service", method = "GET", summary = "GET Capability from service", - responses = {@ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), - @ApiResponse(responseCode = "201", description = "GET Capability"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Get Capability from service", method = "GET", summary = "GET Capability from service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), + @ApiResponse(responseCode = "201", description = "GET Capability"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getCapabilityOnService( - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response getCapabilityOnService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return get(capabilityId, serviceId, request, userId); } @@ -233,56 +205,46 @@ public class CapabilityServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/capabilities/{capabilityId}") - @Operation(description = "Delete capability from service", method = "DELETE", - summary = "Delete capability from service", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Delete capability"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Delete capability from service", method = "DELETE", summary = "Delete capability from service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Delete capability"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteCapabilityOnService( - @Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response deleteCapabilityOnService(@Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return delete(capabilityId, serviceId, request, userId); } - private Response createOrUpdate (String data, String componentType, String componentId, - HttpServletRequest request, - String userId, - boolean isUpdate, - String errorContext) { + private Response createOrUpdate(String data, String componentType, String componentId, HttpServletRequest request, String userId, + boolean isUpdate, String errorContext) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId); try { String componentIdLower = componentId.toLowerCase(); - - Either, ResponseFormat> mappedCapabilitiesDataEither - = getMappedCapabilitiesData(data, modifier, ComponentTypeEnum.findByParamName(componentType)); - if(mappedCapabilitiesDataEither.isRight()) { + Either, ResponseFormat> mappedCapabilitiesDataEither = getMappedCapabilitiesData(data, modifier, + ComponentTypeEnum.findByParamName(componentType)); + if (mappedCapabilitiesDataEither.isRight()) { LOGGER.error("Failed to create or update capabilities"); return buildErrorResponse(mappedCapabilitiesDataEither.right().value()); } List mappedCapabilitiesData = mappedCapabilitiesDataEither.left().value(); Either, ResponseFormat> actionResponse; - if(isUpdate) { - actionResponse = capabilitiesBusinessLogic.updateCapabilities(componentIdLower, - mappedCapabilitiesData, modifier, errorContext, true); + if (isUpdate) { + actionResponse = capabilitiesBusinessLogic.updateCapabilities(componentIdLower, mappedCapabilitiesData, modifier, errorContext, true); } else { - actionResponse = capabilitiesBusinessLogic.createCapabilities(componentIdLower, - mappedCapabilitiesData, modifier, errorContext, true); + actionResponse = capabilitiesBusinessLogic.createCapabilities(componentIdLower, mappedCapabilitiesData, modifier, errorContext, true); } if (actionResponse.isRight()) { LOGGER.error("Failed to create or update capabilities"); return buildErrorResponse(actionResponse.right().value()); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Capabilities create or update"); LOGGER.error("Failed to create or update capabilities with an error", e); @@ -290,20 +252,16 @@ public class CapabilityServlet extends AbstractValidationsServlet { } } - private Response get (String capabilityIdToGet, String componentId, - HttpServletRequest request, String userId){ + private Response get(String capabilityIdToGet, String componentId, HttpServletRequest request, String userId) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); LOGGER.debug("Start get request of {} with modifier id {}", url, userId); - try { String componentIdLower = componentId.toLowerCase(); - Either actionResponse = capabilitiesBusinessLogic - .getCapability(componentIdLower, capabilityIdToGet, modifier, true); + .getCapability(componentIdLower, capabilityIdToGet, modifier, true); if (actionResponse.isRight()) { LOGGER.error("failed to get capability"); return buildErrorResponse(actionResponse.right().value()); @@ -317,21 +275,16 @@ public class CapabilityServlet extends AbstractValidationsServlet { } } - private Response delete (String capabilityId, String componentId, HttpServletRequest - request, String userId){ - + private Response delete(String capabilityId, String componentId, HttpServletRequest request, String userId) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); LOGGER.debug("Start delete request of {} with modifier id {}", url, userId); - try { String componentIdLower = componentId.toLowerCase(); - Either actionResponse = capabilitiesBusinessLogic - .deleteCapability(componentIdLower, capabilityId, modifier, true); + .deleteCapability(componentIdLower, capabilityId, modifier, true); if (actionResponse.isRight()) { LOGGER.error("failed to delete capability"); return buildErrorResponse(actionResponse.right().value()); @@ -346,18 +299,15 @@ public class CapabilityServlet extends AbstractValidationsServlet { } private Either, ResponseFormat> getMappedCapabilitiesData(String inputJson, User user, - ComponentTypeEnum componentTypeEnum){ + ComponentTypeEnum componentTypeEnum) { Either mappedData = getComponentsUtils() - .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, - AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); + .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, + componentTypeEnum); if (mappedData.isRight()) { - return Either.right(getComponentsUtils() - .getResponseFormat(ActionStatus.INVALID_CONTENT)); + return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } - Optional> capabilityDefinitionList = - mappedData.left().value().getCapabilities().values().stream().findFirst(); - return capabilityDefinitionList., ResponseFormat>> - map(Either::left).orElseGet(() -> Either.right(getComponentsUtils() - .getResponseFormat(ActionStatus.GENERAL_ERROR))); + Optional> capabilityDefinitionList = mappedData.left().value().getCapabilities().values().stream().findFirst(); + return capabilityDefinitionList., ResponseFormat>>map(Either::left) + .orElseGet(() -> Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java index 19df0e2cc6..461ddef031 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -63,37 +62,31 @@ import org.slf4j.LoggerFactory; @Singleton public class ComponentAttributeServlet extends BeGenericServlet { + private static final Logger log = LoggerFactory.getLogger(ComponentAttributeServlet.class); + private static final String CREATE_ATTRIBUTE = "Create Attribute"; + private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}"; private final AttributeBusinessLogic attributeBusinessLogic; @Inject - public ComponentAttributeServlet(final UserBusinessLogic userBusinessLogic, - final ComponentsUtils componentsUtils, + public ComponentAttributeServlet(final UserBusinessLogic userBusinessLogic, final ComponentsUtils componentsUtils, final AttributeBusinessLogic attributeBusinessLogic) { super(userBusinessLogic, componentsUtils); this.attributeBusinessLogic = attributeBusinessLogic; } - private static final Logger log = LoggerFactory.getLogger(ComponentAttributeServlet.class); - private static final String CREATE_ATTRIBUTE = "Create Attribute"; - private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}"; - @GET @Path("services/{serviceId}/attributes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Service Attribute", method = "GET", summary = "Returns attribute list of service", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "attribute"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Service attribute not found")}) + @Operation(description = "Get Service Attribute", method = "GET", summary = "Returns attribute list of service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "attribute"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Service attribute not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getAttributeListInService( - @Parameter(description = "service id of attribute", - required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "service id of attribute", required = true) @PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) { - return getAttributeList(serviceId, request, userId); } @@ -101,42 +94,31 @@ public class ComponentAttributeServlet extends BeGenericServlet { @Path("resources/{resourceId}/attributes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Resource Attribute", method = "GET", summary = "Returns attribute list of resource", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "attribute"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Resource attribute not found")}) + @Operation(description = "Get Resource Attribute", method = "GET", summary = "Returns attribute list of resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "attribute"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Resource attribute not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getAttributeListInResource( - @Parameter(description = "resource id of attribute", - required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) { - return getAttributeList(resourceId, request, userId); } private Response getAttributeList(final String componentId, final HttpServletRequest request, final String userId) { - final String url = request.getMethod() + " " + request.getRequestURI(); log.debug(DEBUG_MESSAGE, url, userId); - try { - final Either, ResponseFormat> attributesList = - attributeBusinessLogic.getAttributesList(componentId, userId); - + final Either, ResponseFormat> attributesList = attributeBusinessLogic.getAttributesList(componentId, userId); if (attributesList.isRight()) { return buildErrorResponse(attributesList.right().value()); } - return buildOkResponse(attributesList.left().value()); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_ATTRIBUTE); log.debug("get attribute failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - } 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 49d89c177e..84cb10b2cb 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.core.JsonProcessingException; @@ -117,34 +116,32 @@ import org.springframework.stereotype.Controller; public class ComponentInstanceServlet extends AbstractValidationsServlet { private static final String FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID = "Failed to get properties of component instance ID: {} in {} with ID: {}"; - private static final String GET_GROUP_ARTIFACT_BY_ID = "getGroupArtifactById"; - private static final String GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION = "getGroupArtifactById unexpected exception"; - private static final String GET_START_HANDLE_REQUEST_OF = "(GET) Start handle request of {}"; - private static final String START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS = "Start handle request of updateResourceInstanceProperty. Received property is {}"; - private static final String UPDATE_RESOURCE_INSTANCE = "Update Resource Instance"; - private static final String RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE = "Resource Instance - updateResourceInstance"; - private static final String UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION = "update resource instance with exception"; - private static final String FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT = "Failed to convert received data to BE format."; - private static final String EMPTY_BODY_WAS_SENT = "Empty body was sent."; - private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; - private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}"; + private static final String GET_GROUP_ARTIFACT_BY_ID = "getGroupArtifactById"; + private static final String GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION = "getGroupArtifactById unexpected exception"; + private static final String GET_START_HANDLE_REQUEST_OF = "(GET) Start handle request of {}"; + private static final String START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS = "Start handle request of updateResourceInstanceProperty. Received property is {}"; + private static final String UPDATE_RESOURCE_INSTANCE = "Update Resource Instance"; + private static final String RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE = "Resource Instance - updateResourceInstance"; + private static final String UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION = "update resource instance with exception"; + private static final String FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT = "Failed to convert received data to BE format."; + private static final String EMPTY_BODY_WAS_SENT = "Empty body was sent."; + private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; + private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}"; private static final String CREATE_AND_ASSOCIATE_RI_FAILED_WITH_EXCEPTION = "create and associate RI failed with exception: {}"; - private static final Logger log = Logger.getLogger(ComponentInstanceServlet.class); - private static final Type PROPERTY_CONSTRAINT_TYPE = new TypeToken() {}.getType(); - private static final Gson gsonDeserializer = new GsonBuilder().registerTypeAdapter(PROPERTY_CONSTRAINT_TYPE, new PropertyConstraintDeserialiser()).create(); + private static final Logger log = Logger.getLogger(ComponentInstanceServlet.class); + private static final Type PROPERTY_CONSTRAINT_TYPE = new TypeToken() { + }.getType(); + private static final Gson gsonDeserializer = new GsonBuilder().registerTypeAdapter(PROPERTY_CONSTRAINT_TYPE, new PropertyConstraintDeserialiser()) + .create(); private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ComponentInstanceServlet.class.getName()); private static final String SERVICES = "services"; - private final GroupBusinessLogic groupBL; private final ComponentNodeFilterBusinessLogic nodeFilterBusinessLogic; - @Inject - public ComponentInstanceServlet(UserBusinessLogic userBusinessLogic, - GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - ComponentNodeFilterBusinessLogic nodeFilterBusinessLogic) { + public ComponentInstanceServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL, + ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, ServletUtils servletUtils, + ResourceImportManager resourceImportManager, ComponentNodeFilterBusinessLogic nodeFilterBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.groupBL = groupBL; this.nodeFilterBusinessLogic = nodeFilterBusinessLogic; @@ -154,23 +151,20 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create ComponentInstance", method = "POST", summary = "Returns created ComponentInstance", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Component created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Component instance already exist")}) + @Operation(description = "Create ComponentInstance", method = "POST", summary = "Returns created ComponentInstance", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Component created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Component instance already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createComponentInstance(@Parameter(description = "RI object to be created", required = true) String data, - @PathParam("componentId") final String containerComponentId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME , - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Context final HttpServletRequest request) { - + @PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { validateNotEmptyBody(data); final ComponentInstance componentInstance; try { @@ -180,64 +174,53 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance"); log.debug("create component instance failed with exception", e); - return buildErrorResponse( - getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT, containerComponentType)); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT, containerComponentType)); } - - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INSTANCE, StatusCode.STARTED, - "Starting to create component instance by {}", userId); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_INSTANCE, StatusCode.STARTED, "Starting to create component instance by {}", userId); if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); - return buildErrorResponse( - getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - final ComponentInstance actionResponse = componentInstanceBusinessLogic. - createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance); - loggerSupportability - .log(LoggerSupportabilityActions.CREATE_INSTANCE, actionResponse.getComponentMetadataForSupportLog(), - StatusCode.COMPLETE, "Ending to create component instance by user {}", userId); + final ComponentInstance actionResponse = componentInstanceBusinessLogic + .createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INSTANCE, actionResponse.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Ending to create component instance by user {}", userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse); - } @POST @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource instance updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource instance updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, - @PathParam("componentInstanceId") final String componentInstanceId, - @Parameter(description = "valid values: resources / services / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) throws IOException, BusinessLogicException { - + @PathParam("componentInstanceId") final String componentInstanceId, + @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) throws IOException, BusinessLogicException { final String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE,StatusCode.STARTED,"update Component Instance Metadata"); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.STARTED, "update Component Instance Metadata"); final String userId = request.getHeader(Constants.USER_ID_HEADER); - try { + try { if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, - containerComponentType)); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } componentInstanceBusinessLogic.validateUser(userId); log.debug(START_HANDLE_REQUEST_OF, url); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); - if (bytes == null || bytes.length == 0) { log.info(EMPTY_BODY_WAS_SENT); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } - final String data = new String(bytes); final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); final Either convertResponse = convertToResourceInstance(data); @@ -246,25 +229,21 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT); return buildErrorResponse(convertResponse.right().value()); } - - final ComponentInstance componentInstance = convertResponse.left().value(); final Either actionResponse = componentInstanceBusinessLogic .updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, componentInstance); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE,actionResponse.left().value() - .getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"update Component Instance Metadata by {}", userId); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, actionResponse.left().value().getComponentMetadataForSupportLog(), + StatusCode.COMPLETE, "update Component Instance Metadata by {}", userId); if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } - final ComponentInstance resultValue = actionResponse.left().value(); - if (ComponentTypeEnum.SERVICE.equals(componentTypeEnum) || - ComponentTypeEnum.RESOURCE.equals(componentTypeEnum)) { - if(CollectionUtils.isNotEmpty(componentInstance.getDirectives())) { - final Optional nodeFilterDataDefinition = - nodeFilterBusinessLogic.createNodeFilterIfNotExist(componentId, componentInstanceId, - true, componentTypeEnum); - if (!nodeFilterDataDefinition.isPresent()){ + if (ComponentTypeEnum.SERVICE.equals(componentTypeEnum) || ComponentTypeEnum.RESOURCE.equals(componentTypeEnum)) { + if (CollectionUtils.isNotEmpty(componentInstance.getDirectives())) { + final Optional nodeFilterDataDefinition = nodeFilterBusinessLogic + .createNodeFilterIfNotExist(componentId, componentInstanceId, true, componentTypeEnum); + if (!nodeFilterDataDefinition.isPresent()) { BeEcompErrorManager.getInstance().logBeSystemError("Failed to create node filter."); log.error("Failed to create node filter."); return buildErrorResponse(convertResponse.right().value()); @@ -272,8 +251,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { resultValue.setNodeFilter(nodeFilterDataDefinition.get()); } else { final Optional result = nodeFilterBusinessLogic - .deleteNodeFilterIfExists(componentId, componentInstanceId, true, componentTypeEnum); - if (!result.isPresent()){ + .deleteNodeFilterIfExists(componentId, componentInstanceId, true, componentTypeEnum); + if (!result.isPresent()) { BeEcompErrorManager.getInstance().logBeSystemError("Failed to delete node filter."); log.error("Failed to delete node filter."); return buildErrorResponse(convertResponse.right().value()); @@ -281,97 +260,78 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { resultValue.setNodeFilter(null); } } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE); log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e); throw e; } - } @POST @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update resource instance multiple component", method = "POST", - summary = "Returns updated resource instance", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource instance updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update resource instance multiple component", method = "POST", summary = "Returns updated resource instance", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource instance updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId, @Parameter( - description = "valid values: resources / services / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request, @Parameter(description = "Component Instance JSON Array", - required = true) final String componentInstanceJsonArray) { - + public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId, + @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request, + @Parameter(description = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) { 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); - if (componentInstanceBusinessLogic == 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_UPDATE_RESOURCE_INSTANCE); log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT); return buildErrorResponse(convertResponse.right().value()); } - List componentInstanceList = convertResponse.left().value(); - - List actionResponse = componentInstanceBusinessLogic.updateComponentInstance(containerComponentType, null, componentId, userId, componentInstanceList, true); + List actionResponse = componentInstanceBusinessLogic + .updateComponentInstance(containerComponentType, null, componentId, userId, componentInstanceList, true); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE); log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e); throw e; } - } @DELETE @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete ResourceInstance", method = "DELETE", summary = "Returns delete resourceInstance", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Delete ResourceInstance", method = "DELETE", summary = "Returns delete resourceInstance", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deleteResourceInstance(@PathParam("componentId") final String componentId, - @PathParam("resourceInstanceId") final String resourceInstanceId, - @Parameter(description = "valid values: resources / services / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - + @PathParam("resourceInstanceId") final String resourceInstanceId, + @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); - try { log.debug(START_HANDLE_REQUEST_OF, url); if (componentInstanceBusinessLogic == null) { @@ -379,9 +339,14 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } String userId = request.getHeader(Constants.USER_ID_HEADER); - ComponentInstance actionResponse = componentInstanceBusinessLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId); - loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE,actionResponse.getComponentMetadataForSupportLog(),StatusCode.STARTED,"DELETE_COMPONENT_INSTANCE by user {}", userId); - loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE,actionResponse.getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"DELETE_COMPONENT_INSTANCE by user {}", userId); + ComponentInstance actionResponse = componentInstanceBusinessLogic + .deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId); + loggerSupportability + .log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE, actionResponse.getComponentMetadataForSupportLog(), StatusCode.STARTED, + "DELETE_COMPONENT_INSTANCE by user {}", userId); + loggerSupportability + .log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE, actionResponse.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "DELETE_COMPONENT_INSTANCE by user {}", userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance"); @@ -390,55 +355,48 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } } - @Parameter(description = "allowed values are resources /services / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.PRODUCT_PARAM_NAME}), - required = true) + @Parameter(description = "allowed values are resources /services / products", schema = @Schema(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) - @Operation(description = "Associate RI to RI", method = "POST", summary = "Returns created RelationshipInfo", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Relationship created"), - @ApiResponse(responseCode = "403", description = "Missing information"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Relationship already exist")}) + @Operation(description = "Associate RI to RI", method = "POST", summary = "Returns created RelationshipInfo", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Relationship created"), + @ApiResponse(responseCode = "403", description = "Missing information"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Relationship already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response associateRIToRI(@Parameter( - description = "unique id of the container component") @PathParam("componentId") final String componentId, - @Parameter(description = "allowed values are resources /services / products", - schema = @Schema(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, - @Parameter(description = "RelationshipInfo", required = true) String data, - @Context final HttpServletRequest request) { - + public Response associateRIToRI( + @Parameter(description = "unique id of the container component") @PathParam("componentId") final String componentId, + @Parameter(description = "allowed values are resources /services / products", schema = @Schema(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, @Parameter(description = "RelationshipInfo", required = true) String data, + @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - loggerSupportability.log(LoggerSupportabilityActions.ASSOCIATE_RI_TO_RI, StatusCode.STARTED,"Starting to associate RI To RI for component {} ",componentId + " by " + userId ); + loggerSupportability + .log(LoggerSupportabilityActions.ASSOCIATE_RI_TO_RI, StatusCode.STARTED, "Starting to associate RI To RI for component {} ", + componentId + " by " + userId); try { - log.debug(START_HANDLE_REQUEST_OF, url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - RequirementCapabilityRelDef requirementDef = convertToRequirementCapabilityRelDef(data); requirementDef.setOriginUI(true); - - RequirementCapabilityRelDef actionResponse = componentInstanceBusinessLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum); - loggerSupportability.log(LoggerSupportabilityActions.ASSOCIATE_RI_TO_RI, StatusCode.COMPLETE,"Ended associate RI To RI for component {} ",componentId + " by " + userId ); + RequirementCapabilityRelDef actionResponse = componentInstanceBusinessLogic + .associateRIToRI(componentId, userId, requirementDef, componentTypeEnum); + loggerSupportability + .log(LoggerSupportabilityActions.ASSOCIATE_RI_TO_RI, StatusCode.COMPLETE, "Ended associate RI To RI for component {} ", + componentId + " by " + userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse); - } catch (Exception e) { - if(!e.getClass().equals(ComponentException.class)) { + if (!e.getClass().equals(ComponentException.class)) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance"); log.debug("associate resource instance to another RI with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); @@ -451,42 +409,38 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Dissociate RI from RI", method = "PUT", summary = "Returns deleted RelationshipInfo", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Relationship deleted"), - @ApiResponse(responseCode = "403", description = "Missing information"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Dissociate RI from RI", method = "PUT", summary = "Returns deleted RelationshipInfo", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Relationship deleted"), + @ApiResponse(responseCode = "403", description = "Missing information"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response dissociateRIFromRI( - @Parameter(description = "allowed values are resources /services / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME}), - required = true) @PathParam("containerComponentType") final String containerComponentType, - @Parameter( - description = "unique id of the container component") @PathParam("componentId") final String componentId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "RelationshipInfo", required = true) String data, - @Context final HttpServletRequest request) { - + @Parameter(description = "allowed values are resources /services / products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam("containerComponentType") final String containerComponentType, + @Parameter(description = "unique id of the container component") @PathParam("componentId") final String componentId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Parameter(description = "RelationshipInfo", required = true) String data, + @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - loggerSupportability.log(LoggerSupportabilityActions.UN_ASSOCIATE_RI_TO_RI, StatusCode.STARTED,"Starting to undo associate RI To RI for component {} ",componentId + " by " + userId ); + loggerSupportability + .log(LoggerSupportabilityActions.UN_ASSOCIATE_RI_TO_RI, StatusCode.STARTED, "Starting to undo associate RI To RI for component {} ", + componentId + " by " + userId); try { - log.debug(START_HANDLE_REQUEST_OF, url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - RequirementCapabilityRelDef requirementDef = convertToRequirementCapabilityRelDef(data); - RequirementCapabilityRelDef actionResponse = componentInstanceBusinessLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum); - loggerSupportability.log(LoggerSupportabilityActions.UN_ASSOCIATE_RI_TO_RI, StatusCode.COMPLETE,"Ended undo associate RI To RI for component {} ",componentId + " by " + userId ); + RequirementCapabilityRelDef actionResponse = componentInstanceBusinessLogic + .dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum); + loggerSupportability + .log(LoggerSupportabilityActions.UN_ASSOCIATE_RI_TO_RI, StatusCode.COMPLETE, "Ended undo associate RI To RI for component {} ", + componentId + " by " + userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance"); log.debug("dissociate resource instance from service failed with exception", e); @@ -498,56 +452,46 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create RI and associate RI to RI", method = "POST", - summary = "Returns created RI and RelationshipInfo", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "RI created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Relationship already exist")}) + @Operation(description = "Create RI and associate RI to RI", method = "POST", summary = "Returns created RI and RelationshipInfo", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "RI created"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Relationship already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId, @Parameter( - description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) throws IOException { - + public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) throws IOException { 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); - if (componentInstanceBusinessLogic == 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())); + Either formattedResponse = Either + .right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); return buildErrorResponse(formattedResponse.right().value()); } - CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value(); RequirementCapabilityRelDef requirementDef = createAndAssotiateInfo.getAssociate(); requirementDef.setOriginUI(true); - Either actionResponse = componentInstanceBusinessLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo); - + Either actionResponse = componentInstanceBusinessLogic + .createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo); if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } @@ -563,65 +507,62 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update resource instance property", method = "POST", - summary = "Returns updated resource instance property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource instance created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update resource instance property", method = "POST", summary = "Returns updated resource instance property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource instance created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateResourceInstanceProperties( - @Parameter(description = "service id") @PathParam("componentId") final String componentId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Parameter( - description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, - @Parameter(description = "id of user initiating the operation") @HeaderParam( - value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request, - @Parameter(description = "Component Instance Properties JSON Array", - required = true) final String componentInstancePropertiesJsonArray) { - + public Response updateResourceInstanceProperties(@Parameter(description = "service id") @PathParam("componentId") final String componentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, + @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request, + @Parameter(description = "Component Instance Properties JSON Array", required = true) final String componentInstancePropertiesJsonArray) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.STARTED,"Starting to update Resource Instance Properties for component {} ",componentId + " by " + userId ); - + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.STARTED, + "Starting to update Resource Instance Properties for component {} ", componentId + " by " + userId); Wrapper errorWrapper = new Wrapper<>(); List propertiesToUpdate = new ArrayList<>(); if (errorWrapper.isEmpty()) { - Either, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(componentInstancePropertiesJsonArray); - if (propertiesToUpdateEither.isRight()) { - errorWrapper.setInnerElement(propertiesToUpdateEither.right().value()); - } else { - propertiesToUpdate = propertiesToUpdateEither.left().value(); - } + Either, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties( + componentInstancePropertiesJsonArray); + if (propertiesToUpdateEither.isRight()) { + errorWrapper.setInnerElement(propertiesToUpdateEither.right().value()); + } else { + propertiesToUpdate = propertiesToUpdateEither.left().value(); + } } if (!errorWrapper.isEmpty()) { - return buildErrorResponse(errorWrapper.getInnerElement()); + return buildErrorResponse(errorWrapper.getInnerElement()); } log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, propertiesToUpdate); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); if (componentInstanceBusinessLogic == null) { - log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - Either, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId); + Either, ResponseFormat> actionResponse = componentInstanceBusinessLogic + .createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId); if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); + return buildErrorResponse(actionResponse.right().value()); } List resourceInstanceProperties = actionResponse.left().value(); ObjectMapper mapper = new ObjectMapper(); String result; - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.COMPLETE,"Ended update Resource Instance Properties for component {} ",componentId + " by " + userId ); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.COMPLETE, + "Ended update Resource Instance Properties for component {} ", componentId + " by " + userId); try { result = mapper.writeValueAsString(resourceInstanceProperties); } catch (JsonProcessingException e) { log.error(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e.getMessage(), e); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.COMPLETE,"Ended update Resource Instance Properties for component {} ",componentId + " by user " + userId ); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.COMPLETE, + "Ended update Resource Instance Properties for component {} ", componentId + " by user " + userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } @@ -629,66 +570,62 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/inputs") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update resource instance property", method = "POST", - summary = "Returns updated resource instance property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource instance created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update resource instance property", method = "POST", summary = "Returns updated resource instance property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource instance created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateResourceInstanceInput( - @Parameter(description = "service id") @PathParam("componentId") final String componentId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Parameter( - description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, - @Parameter(description = "id of user initiating the operation") @HeaderParam( - value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request, - @Parameter(description = "Component Instance Properties JSON Array", - required = true) final String componentInstanceInputsJsonArray) { - + public Response updateResourceInstanceInput(@Parameter(description = "service id") @PathParam("componentId") final String componentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, + @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request, + @Parameter(description = "Component Instance Properties JSON Array", required = true) final String componentInstanceInputsJsonArray) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - 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(); - } + 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()); + return buildErrorResponse(errorWrapper.getInnerElement()); } log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, inputsToUpdate); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); if (componentInstanceBusinessLogic == null) { - log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - Either, ResponseFormat> actionResponse = - componentInstanceBusinessLogic.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId); + Either, ResponseFormat> actionResponse = componentInstanceBusinessLogic + .createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId); if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); + return buildErrorResponse(actionResponse.right().value()); } List resourceInstanceInput = actionResponse.left().value(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); String result; - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE,"Ending update Resource Instance Input for component {} ",componentId + " by " + userId ); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ending update Resource Instance Input for component {} ", + componentId + " by " + userId); try { result = mapper.writeValueAsString(resourceInstanceInput); } catch (JsonProcessingException e) { log.error(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e.getMessage(), e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ending update Resource Instance Input for component {} ", componentId + " by user " + userId); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ending update Resource Instance Input for component {} ", + componentId + " by user " + userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } @@ -706,102 +643,92 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update resource instance attribute", method = "POST", - summary = "Returns updated resource instance attribute", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource instance created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update resource instance attribute", method = "POST", summary = "Returns updated resource instance attribute", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource instance created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateResourceInstanceAttribute( - @Parameter(description = "service id") @PathParam("componentId") final String componentId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Parameter( - description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, - @Parameter(description = "id of user initiating the operation") @HeaderParam( - value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) throws IOException { - + public Response updateResourceInstanceAttribute(@Parameter(description = "service id") @PathParam("componentId") final String componentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, + @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.STARTED,"Starting to update Resource Instance Attribute for component {} ",componentId + " by " + userId ); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.STARTED, "Starting to update Resource Instance Attribute for component {} ", + componentId + " by " + userId); 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); + Either eitherAttribute = componentInstanceLogic + .createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); if (eitherAttribute.isRight()) { errorWrapper.setInnerElement(eitherAttribute.right().value()); } else { attributeWrapper.setInnerElement(eitherAttribute.left().value()); } } - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.COMPLETE,"Ended update Resource Instance Attribute for component {} ",componentId + " by " + userId ); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.COMPLETE, "Ended update Resource Instance Attribute for component {} ", + componentId + " by " + userId); return buildResponseFromElement(errorWrapper, attributeWrapper); - } catch (Exception e) { log.error(CREATE_AND_ASSOCIATE_RI_FAILED_WITH_EXCEPTION, e.getMessage(), e); throw e; } - } @DELETE @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update resource instance", method = "DELETE", - summary = "Returns deleted resource instance property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource instance created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update resource instance", method = "DELETE", summary = "Returns deleted resource instance property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource instance created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteResourceInstanceProperty( - @Parameter(description = "service id") @PathParam("componentId") final String componentId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Parameter( - description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, - @Parameter(description = "property id") @PathParam("propertyId") final String propertyId, - @Parameter(description = "id of user initiating the operation") @HeaderParam( - value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - - - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED,"Starting to delete Resource Instance Property for component {} ",componentId + " by " + userId ); + public Response deleteResourceInstanceProperty(@Parameter(description = "service id") @PathParam("componentId") final String componentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, + @Parameter(description = "property id") @PathParam("propertyId") final String propertyId, + @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED, "Starting to delete Resource Instance Property for component {} ", + componentId + " by " + userId); String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE,"Ended delete Resource Instance Property for component {} ",componentId + " by " + userId ); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ended delete Resource Instance Property for component {} ", + componentId + " by " + userId); if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - - Either actionResponse = componentInstanceBusinessLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId); + Either actionResponse = componentInstanceBusinessLogic + .deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId); if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } @@ -810,133 +737,108 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { log.error(CREATE_AND_ASSOCIATE_RI_FAILED_WITH_EXCEPTION, e.getMessage(), e); throw e; } - } @POST @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource instance created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource instance created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, - @PathParam("componentInstanceId") final String componentInstanceId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) throws IOException { - + @PathParam("componentInstanceId") final String componentInstanceId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try ( - InputStream inputStream = request.getInputStream()) { - + 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); - if (componentInstanceBusinessLogic == 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_UPDATE_RESOURCE_INSTANCE); log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT); return buildErrorResponse(convertResponse.right().value()); } - ComponentInstance newResourceInstance = convertResponse.left().value(); - ComponentInstance actionResponse = componentInstanceBusinessLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance); - + ComponentInstance actionResponse = componentInstanceBusinessLogic + .changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE); log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e); throw e; } - } @POST @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update resource instance property", method = "POST", - summary = "Returns updated resource instance property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource instance created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update resource instance property", method = "POST", summary = "Returns updated resource instance property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource instance created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateGroupInstanceProperty( - @Parameter(description = "service id") @PathParam("componentId") final String componentId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Parameter( - description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, - @Parameter(description = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId, - @Parameter(description = "id of user initiating the operation") @HeaderParam( - value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) throws IOException { - + public Response updateGroupInstanceProperty(@Parameter(description = "service id") @PathParam("componentId") final String componentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, + @Parameter(description = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId, + @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED,"Starting update Group Instance Property for component {} ",componentId + " by " + userId ); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED, "Starting update Group Instance Property for component {} ", + componentId + " by " + userId); 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_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, property); - - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - - Either actionResponse = componentInstanceBusinessLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId); + Either actionResponse = componentInstanceBusinessLogic + .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); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE,"Ended update Group Instance Property for component {} ",componentId + " by " + userId ); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ended update Group Instance Property for component {} ", + componentId + " by " + userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (Exception e) { log.error(CREATE_AND_ASSOCIATE_RI_FAILED_WITH_EXCEPTION, e.getMessage(), e); throw e; @@ -947,39 +849,32 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get group artifacts ", method = "GET", - summary = "Returns artifacts metadata according to groupInstId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "group found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Group not found")}) + @Operation(description = "Get group artifacts ", method = "GET", summary = "Returns artifacts metadata according to groupInstId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "group found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Group not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { + @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) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(GET_START_HANDLE_REQUEST_OF, url); - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either actionResponse = groupBL.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false); - + Either actionResponse = groupBL + .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(GET_GROUP_ARTIFACT_BY_ID); log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e); throw e; } - } // US831698 @@ -987,23 +882,21 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get component instance properties", method = "GET", - summary = "Returns component instance properties", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Properties found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")}) + @Operation(description = "Get component instance properties", method = "GET", summary = "Returns component instance properties", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Properties found"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { - - + @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(GET_START_HANDLE_REQUEST_OF, url); - - List componentInstancePropertiesById = componentInstanceBusinessLogic.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId); + List componentInstancePropertiesById = componentInstanceBusinessLogic + .getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById); } @@ -1011,21 +904,19 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/attributes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get component instance attributes", method = "GET", - summary = "Returns component instance attributes", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Attributes found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")}) + @Operation(description = "Get component instance attributes", method = "GET", summary = "Returns component instance attributes", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Attributes found"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getInstanceAttributesById(@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) final String userId) { - + @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) { final String url = request.getMethod() + " " + request.getRequestURI(); log.debug(GET_START_HANDLE_REQUEST_OF, url); - final List componentInstanceAttributesById = componentInstanceBusinessLogic .getComponentInstanceAttributesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstanceAttributesById); @@ -1036,36 +927,31 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get component instance capability properties", method = "GET", - summary = "Returns component instance capability properties", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Properties found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")}) + @Operation(description = "Get component instance capability properties", method = "GET", summary = "Returns component instance capability properties", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Properties found"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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) { - - + 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) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(GET_START_HANDLE_REQUEST_OF, url); - try { - List componentInstancePropertiesById = componentInstanceBusinessLogic.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, - capabilityType, capabilityName, ownerId, userId); - + List componentInstancePropertiesById = componentInstanceBusinessLogic + .getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, capabilityType, + capabilityName, ownerId, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID); log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e); throw e; } - } //US 331281 @@ -1073,25 +959,26 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Instance Capabilty Property", method = "PUT", - summary = "Returns updated property", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource instance capabilty property updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")}) + @Operation(description = "Update Instance Capabilty Property", method = "PUT", summary = "Returns updated property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource instance capabilty property updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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, - @Parameter(description = "Instance capabilty property to update", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + 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, + @Parameter(description = "Instance capabilty property to update", required = true) String data, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(PUT) Start handle request of {}", url); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY_PROPERTY, StatusCode.STARTED," Starting to update Instance Capability Property for component instance {} " , componentInstanceUniqueId + " by " + userId); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY_PROPERTY, StatusCode.STARTED, + " Starting to update Instance Capability Property for component instance {} ", componentInstanceUniqueId + " by " + userId); try { Wrapper errorWrapper = new Wrapper<>(); List propertiesToUpdate = new ArrayList<>(); @@ -1103,20 +990,20 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { propertiesToUpdate = propertiesToUpdateEither.left().value(); } } - if (!errorWrapper.isEmpty()) { return buildErrorResponse(errorWrapper.getInnerElement()); } - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - - Either, ResponseFormat> updateCICapProperty = componentInstanceBusinessLogic.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, propertiesToUpdate, userId); - + Either, ResponseFormat> updateCICapProperty = componentInstanceBusinessLogic + .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); + log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType, + containerComponentId); return buildErrorResponse(updateCICapProperty.right().value()); } - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY_PROPERTY, StatusCode.COMPLETE," Ended to update Instance Capability Property for component instance {} " , componentInstanceUniqueId + " by " + userId); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY_PROPERTY, StatusCode.COMPLETE, + " Ended to update Instance Capability Property for component instance {} ", componentInstanceUniqueId + " by " + userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateCICapProperty.left().value()); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID); @@ -1124,55 +1011,50 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { throw e; } } - + @PUT @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/requirement/{capabilityType}/requirementName/{requirementName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Instance Requirement", method = "PUT", - summary = "Returns updated requirement", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource instance requirement updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Component/Component Instance/Requirement - not found")}) + @Operation(description = "Update Instance Requirement", method = "PUT", summary = "Returns updated requirement", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource instance requirement updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Component/Component Instance/Requirement - not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateInstanceRequirement( - @PathParam("containerComponentType") final String containerComponentType, - @PathParam("containerComponentId") final String containerComponentId, - @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, - @PathParam("capabilityType") final String capabilityType, - @PathParam("requirementName") final String requirementName, - @Parameter(description = "Instance capabilty requirement to update", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response updateInstanceRequirement(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, + @PathParam("capabilityType") final String capabilityType, + @PathParam("requirementName") final String requirementName, + @Parameter(description = "Instance capabilty requirement to update", required = true) String data, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_REQUIREMENT, StatusCode.STARTED,"Starting to update requirement {} in component instance {} by {}", requirementName, componentInstanceUniqueId, userId ); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_REQUIREMENT, StatusCode.STARTED, + "Starting to update requirement {} in component instance {} by {}", requirementName, componentInstanceUniqueId, userId); try { - log.debug(START_HANDLE_REQUEST_OF, url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - - Either mappedRequirementDataEither = getMappedRequirementData(data, new User(userId), componentTypeEnum); - if(mappedRequirementDataEither.isRight()) { + Either mappedRequirementDataEither = getMappedRequirementData(data, new User(userId), + componentTypeEnum); + if (mappedRequirementDataEither.isRight()) { log.debug("Failed to update requirements"); return buildErrorResponse(mappedRequirementDataEither.right().value()); } RequirementDefinition requirementDef = mappedRequirementDataEither.left().value(); - - Either response = componentInstanceBusinessLogic.updateInstanceRequirement(componentTypeEnum, containerComponentId, componentInstanceUniqueId, - requirementDef, userId); - + Either response = componentInstanceBusinessLogic + .updateInstanceRequirement(componentTypeEnum, containerComponentId, componentInstanceUniqueId, requirementDef, userId); if (response.isRight()) { return buildErrorResponse(response.right().value()); } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), response.left().value()); - } catch (ComponentException e) { throw e; } catch (Exception e) { @@ -1181,35 +1063,32 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - - private Either getMappedRequirementData(String inputJson, User user, - ComponentTypeEnum componentTypeEnum){ - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user, RequirementDefinition.class, AuditingActionEnum.GET_TOSCA_MODEL, componentTypeEnum); + + private Either getMappedRequirementData(String inputJson, User user, ComponentTypeEnum componentTypeEnum) { + return getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(inputJson, user, RequirementDefinition.class, AuditingActionEnum.GET_TOSCA_MODEL, + componentTypeEnum); } @POST @Path("/{containerComponentType}/{containerComponentId}/serviceProxy") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create service proxy", method = "POST", summary = "Returns created service proxy", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Service proxy created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Service proxy already exist")}) + @Operation(description = "Create service proxy", method = "POST", summary = "Returns created service proxy", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Service proxy created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Service proxy already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createServiceProxy(@Parameter(description = "RI object to be created", required = true) String data, - @PathParam("containerComponentId") final String containerComponentId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Context final HttpServletRequest request) { - + @PathParam("containerComponentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { try { - ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); componentInstance.setInvariantName(null); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); @@ -1222,12 +1101,10 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } Either actionResponse = componentInstanceBusinessLogic.createServiceProxy(); - 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); @@ -1239,20 +1116,18 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete service proxy", method = "DELETE", summary = "Returns delete service proxy", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Service proxy deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Delete service proxy", method = "DELETE", summary = "Returns delete service proxy", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Service proxy deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, - @PathParam("serviceProxyId") final String serviceProxyId, - @Parameter(description = "valid values: resources / services / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - + @PathParam("serviceProxyId") final String serviceProxyId, + @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); try { log.debug(START_HANDLE_REQUEST_OF, url); @@ -1261,7 +1136,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } Either actionResponse = componentInstanceBusinessLogic.deleteServiceProxy(); - if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } else { @@ -1278,21 +1152,18 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update service proxy with new version", method = "POST", - summary = "Returns updated service proxy", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Service proxy created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update service proxy with new version", method = "POST", summary = "Returns updated service proxy", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Service proxy created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, - @PathParam("serviceProxyId") final String serviceProxyId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - - + @PathParam("serviceProxyId") final String serviceProxyId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); try { @@ -1301,21 +1172,20 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } Either actionResponse = componentInstanceBusinessLogic.changeServiceProxyVersion(); - 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); throw e; } } + /** - * REST API GET relation by Id - * Allows to get relation contained in specified component according to received Id + * REST API GET relation by Id Allows to get relation contained in specified component according to received Id + * * @param containerComponentType * @param componentId * @param relationId @@ -1327,18 +1197,14 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/relationId/{relationId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get relation", method = "GET", - summary = "Returns relation metadata according to relationId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "relation found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Relation not found")}) + @Operation(description = "Get relation", method = "GET", summary = "Returns relation metadata according to relationId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "relation found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Relation not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { - - + @PathParam("componentId") final String componentId, @PathParam("relationId") final String relationId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(GET_START_HANDLE_REQUEST_OF, url); try { @@ -1347,8 +1213,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - - Either actionResponse = componentInstanceBusinessLogic.getRelationById(componentId, relationId, userId, componentTypeEnum); + Either actionResponse = componentInstanceBusinessLogic + .getRelationById(componentId, relationId, userId, componentTypeEnum); if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } @@ -1361,23 +1227,21 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } private Either convertToResourceInstance(String data) { - - Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + 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); + 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())); } @@ -1385,7 +1249,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { if (StringUtils.isEmpty(dataList)) { return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_BODY)); } - Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + Either convertStatus = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); if (convertStatus.isRight()) { return Either.right(convertStatus.right().value()); } @@ -1396,16 +1261,15 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { if (StringUtils.isEmpty(dataList)) { return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_BODY)); } - Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceInput[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + 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 RequirementCapabilityRelDef convertToRequirementCapabilityRelDef(String data) { - Either convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class); if (convertStatus.isRight()) { throw new ByActionStatusComponentException(convertStatus.right().value()); @@ -1433,29 +1297,24 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } } - @GET @Path("/{containerComponentType}/{componentId}/paths-to-delete") @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Check if forwarding path to delete on version change", method = "GET", - summary = "Returns forwarding paths to delete", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))}) - public Response changeResourceInstanceVersion( @PathParam("componentId") String componentId, - @QueryParam("componentInstanceId") final String oldComponentInstanceId, - @QueryParam("newComponentInstanceId") final String newComponentInstanceId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(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)); + @Operation(description = "Check if forwarding path to delete on version change", method = "GET", summary = "Returns forwarding paths to delete", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))}) + public Response changeResourceInstanceVersion(@PathParam("componentId") String componentId, + @QueryParam("componentInstanceId") final String oldComponentInstanceId, + @QueryParam("newComponentInstanceId") final String newComponentInstanceId, + @Parameter(description = "valid values: resources / services", schema = @Schema(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)); + if (newComponentInstanceId == null) { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_NEW_COMPONENT_INSTANCE)); } - - String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); if (componentInstanceBusinessLogic == null) { @@ -1463,43 +1322,39 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { 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{ + 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= componentInstanceBusinessLogic.forwardingPathOnVersionChange( - containerComponentType,componentId,oldComponentInstanceId,newComponentInstance); + Either, ResponseFormat> actionResponse = componentInstanceBusinessLogic + .forwardingPathOnVersionChange(containerComponentType, componentId, oldComponentInstanceId, newComponentInstance); if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } - ForwardingPaths forwardingPaths=new ForwardingPaths(); + ForwardingPaths forwardingPaths = new ForwardingPaths(); forwardingPaths.setForwardingPathToDelete(actionResponse.left().value()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), forwardingPaths); - } @POST @Path("/services/{componentId}/copyComponentInstance/{componentInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces((MediaType.APPLICATION_JSON)) - @Operation(description = "Copy Component Instance", method = "POST", - summary = "Returns updated service information", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "201", description = "Copy and Paste Success"), - @ApiResponse(responseCode = "403", description = "Restricted Operation"), - @ApiResponse(responseCode = "400", description = "Invalid Content / Missing content")}) + @Operation(description = "Copy Component Instance", method = "POST", summary = "Returns updated service information", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "201", description = "Copy and Paste Success"), + @ApiResponse(responseCode = "403", description = "Restricted Operation"), + @ApiResponse(responseCode = "400", description = "Invalid Content / Missing content")}) public Response copyComponentInstance( - @Parameter(description = "service unique id in pasted canvas") @PathParam("componentId") final String containerComponentId, - @Parameter(description = "Data for copying", required = true) String data, @PathParam("componentInstanceId") final String componentInstanceId, - @Context final HttpServletRequest request) { + @Parameter(description = "service unique id in pasted canvas") @PathParam("componentId") final String containerComponentId, + @Parameter(description = "Data for copying", required = true) String data, @PathParam("componentInstanceId") final String componentInstanceId, + @Context final HttpServletRequest request) { log.info("Start to copy component instance"); - String userId = request.getHeader(Constants.USER_ID_HEADER); final String CNTAINER_CMPT_TYPE = SERVICES; - try { ComponentInstance inputComponentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); inputComponentInstance.setInvariantName(null); @@ -1508,20 +1363,17 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { log.debug(UNSUPPORTED_COMPONENT_TYPE, componentTypeEnum); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, SERVICES)); } - Either, ResponseFormat> copyComponentInstance = componentInstanceBusinessLogic.copyComponentInstance( - inputComponentInstance, containerComponentId, componentInstanceId, userId); - + Either, ResponseFormat> copyComponentInstance = componentInstanceBusinessLogic + .copyComponentInstance(inputComponentInstance, containerComponentId, componentInstanceId, userId); if (copyComponentInstance.isRight()) { log.error("Failed to copy ComponentInstance {}", copyComponentInstance.right().value()); return buildErrorResponse(copyComponentInstance.right().value()); } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - copyComponentInstance.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), copyComponentInstance.left().value()); } catch (Exception e) { log.error("Failed to convert json to Map { }", data, e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.USER_DEFINED, - "Failed to get the copied component instance information")); + return buildErrorResponse( + getComponentsUtils().getResponseFormat(ActionStatus.USER_DEFINED, "Failed to get the copied component instance information")); } } @@ -1529,101 +1381,79 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/batchDeleteResourceInstances/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Batch Delete ResourceInstances", method = "POST", - responses = {@ApiResponse(responseCode = "203", description = "ResourceInstances deleted"), - @ApiResponse(responseCode = "403", description = "Restricted Operation"), - @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")}) + @Operation(description = "Batch Delete ResourceInstances", method = "POST", responses = { + @ApiResponse(responseCode = "203", description = "ResourceInstances deleted"), + @ApiResponse(responseCode = "403", description = "Restricted Operation"), + @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")}) public Response batchDeleteResourceInstances( - @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.PRODUCT_PARAM_NAME})) - @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, - @Context final HttpServletRequest request, - @Parameter(description = "Component Instance Id List", required = true) final String componentInstanceIdLisStr) { + @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @Parameter(description = "Component Instance Id List", required = true) final String componentInstanceIdLisStr) { try { if (componentInstanceIdLisStr == null || componentInstanceIdLisStr.isEmpty()) { - log.error("Empty JSON List was sent",componentInstanceIdLisStr); + log.error("Empty JSON List was sent", componentInstanceIdLisStr); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } - - if (componentInstanceBusinessLogic == null) { log.error(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - Either, ResponseFormat> convertResponse = convertToStringList(componentInstanceIdLisStr); - if (convertResponse.isRight()) { BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - batchDeleteResourceInstances"); log.error(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT); return buildErrorResponse(convertResponse.right().value()); } - String userId = request.getHeader(Constants.USER_ID_HEADER); List componentInstanceIdList = convertResponse.left().value(); log.debug("batchDeleteResourceInstances componentInstanceIdList is {}", componentInstanceIdList); - Map> deleteErrorMap = componentInstanceBusinessLogic.batchDeleteComponentInstance(containerComponentType, - componentId, componentInstanceIdList, userId); - + Map> deleteErrorMap = componentInstanceBusinessLogic + .batchDeleteComponentInstance(containerComponentType, componentId, componentInstanceIdList, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteErrorMap); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Batch Delete ResourceInstances"); - log.error("batch delete resource instances with exception" , e); + log.error("batch delete resource instances with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - } @PUT @Path("/{containerComponentType}/{componentId}/resourceInstance/batchDissociate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Batch Dissociate RI from RI", method = "PUT", - summary = "Returns deleted RelationShip Info", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Relationship deleted"), - @ApiResponse(responseCode = "403", description = "Missing Information"), - @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")}) + @Operation(description = "Batch Dissociate RI from RI", method = "PUT", summary = "Returns deleted RelationShip Info", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Relationship deleted"), + @ApiResponse(responseCode = "403", description = "Missing Information"), + @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")}) public Response batchDissociateRIFromRI( - @Parameter(description = "allowed values are resources/services/products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.PRODUCT_PARAM_NAME}), - required = true) @PathParam("containerComponentType") final String containerComponentType, - @Parameter( - description = "unique id of the container component") @PathParam("componentId") final String componentId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "RelationshipInfo", required = true) String data, - @Context final HttpServletRequest request) { - - + @Parameter(description = "allowed values are resources/services/products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam("containerComponentType") final String containerComponentType, + @Parameter(description = "unique id of the container component") @PathParam("componentId") final String componentId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Parameter(description = "RelationshipInfo", required = true) String data, + @Context final HttpServletRequest request) { try { if (data == null || data.length() == 0) { log.info("Empty JSON list was sent"); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - Either, ResponseFormat> regInfoWs = convertToRequirementCapabilityRelDefList(data); - if (regInfoWs.isRight()) { BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - batch dissociateRIFromRI"); log.debug("Failed to convert received data to BE format"); return buildErrorResponse(regInfoWs.right().value()); } - List requirementDefList = regInfoWs.left().value(); - List delOkResult = componentInstanceBusinessLogic.batchDissociateRIFromRI( - componentId, userId, requirementDefList, componentTypeEnum); - + List delOkResult = componentInstanceBusinessLogic + .batchDissociateRIFromRI(componentId, userId, requirementDefList, componentTypeEnum); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), delOkResult); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Batch Dissociate Resource Instance"); @@ -1633,79 +1463,59 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } private Either, ResponseFormat> convertToStringList(String datalist) { - Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(datalist, new User(), String[].class, null, null); - + Either convertStatus = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(datalist, new User(), String[].class, null, null); if (convertStatus.isRight()) { return Either.right(convertStatus.right().value()); } - return Either.left(Arrays.asList(convertStatus.left().value())); } private Either, ResponseFormat> convertToRequirementCapabilityRelDefList(String data) { - Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), RequirementCapabilityRelDef[].class, null, null); - + Either convertStatus = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(data, new User(), RequirementCapabilityRelDef[].class, null, null); if (convertStatus.isRight()) { return Either.right(convertStatus.right().value()); } - return Either.left(Arrays.asList(convertStatus.left().value())); } @POST @Path("/services/replaceVNF") - @Operation(description = "Replace new VNF based on the existing VNF", method = "POST", - summary = "Return whether the replace VNF is successful", responses = { - @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = ReplaceVNFInfo.class)))), - @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(responseCode = "401", - description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), - @ApiResponse(responseCode = "404", - description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(responseCode = "405", - description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(responseCode = "500", - description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(responseCode = "409", description = "Service already exist")}) + @Operation(description = "Replace new VNF based on the existing VNF", method = "POST", summary = "Return whether the replace VNF is successful", responses = { + @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ReplaceVNFInfo.class)))), + @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"), + @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(responseCode = "409", description = "Service already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response replaceVNF( - @Parameter(description = "The user id", - required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) - @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Context final HttpServletRequest request, - @Parameter(description = "Resource object to be created", required = true) String data) { - + public Response replaceVNF(@Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Context final HttpServletRequest request, + @Parameter(description = "Resource object to be created", required = true) String data) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("replaceVNF: Start handle request of {}", url); User modifier = new User(); modifier.setUserId(userId); log.debug("replaceVNF:modifier id is {}", userId); validateNotEmptyBody(data); - Either convertResponse = parseToReplaceVNFInfo(data, modifier); if (convertResponse.isRight()) { throw new ByResponseFormatComponentException(convertResponse.right().value()); } - log.debug("replaceVNF:get ReplaceVNFInfo success"); - String containerComponentType = SERVICES; ReplaceVNFInfo replaceVNFInfo = convertResponse.left().value(); String serviceUniqueId = replaceVNFInfo.getServiceUniqueId(); String abstractResourceUniqueId = replaceVNFInfo.getAbstractResourceUniqueId(); - ComponentInstance componentInstance = replaceVNFInfo.getRealVNFComponentInstance(); - log.debug("replaceVNF:get ReplaceVNFInfo,serviceUniqueId:{},abstractResourceUniqueId:{}", - serviceUniqueId,abstractResourceUniqueId); + log.debug("replaceVNF:get ReplaceVNFInfo,serviceUniqueId:{},abstractResourceUniqueId:{}", serviceUniqueId, abstractResourceUniqueId); try { /** * delete vnf @@ -1714,7 +1524,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { log.debug("replaceVNF:Unsupported component type {}", containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); } - Either componentInstanceEither = componentInstanceBusinessLogic.deleteAbstractComponentInstance(containerComponentType, serviceUniqueId, abstractResourceUniqueId, userId); + Either componentInstanceEither = componentInstanceBusinessLogic + .deleteAbstractComponentInstance(containerComponentType, serviceUniqueId, abstractResourceUniqueId, userId); if (componentInstanceEither.isRight()) { log.debug("replaceVNF:delete Abstract ComponentInstance field"); return buildErrorResponse(componentInstanceEither.right().value()); @@ -1725,15 +1536,14 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { log.debug("replaceVNF,start add vnf"); componentInstance.setInvariantName(null); componentInstance.setCreatedFrom(CreatedFrom.UI); - - Either realComponentInstance = componentInstanceBusinessLogic.createRealComponentInstance(containerComponentType, serviceUniqueId, userId, componentInstance); + Either realComponentInstance = componentInstanceBusinessLogic + .createRealComponentInstance(containerComponentType, serviceUniqueId, userId, componentInstance); if (realComponentInstance.isRight()) { log.debug("replaceVNF:filed to add vnf"); return buildErrorResponse(realComponentInstance.right().value()); } ComponentInstance newComponentInstance = realComponentInstance.left().value(); log.debug("replaceVNF:success to add vnf"); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), newComponentInstance); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("replaceVNF"); @@ -1743,8 +1553,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } private Either parseToReplaceVNFInfo(String serviceJson, User user) { - log.debug("enter parseToReplaceVNFInfo,get serviceJson:{}",serviceJson); - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ReplaceVNFInfo.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + log.debug("enter parseToReplaceVNFInfo,get serviceJson:{}", serviceJson); + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ReplaceVNFInfo.class, AuditingActionEnum.CREATE_RESOURCE, + ComponentTypeEnum.SERVICE); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInterfaceOperationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInterfaceOperationServlet.java index c2e668c049..4d94ffc8d7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInterfaceOperationServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInterfaceOperationServlet.java @@ -18,7 +18,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import fj.data.Either; @@ -74,24 +73,17 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationServlet.class); private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}"; private static final String MODIFIER_ID_IS = "modifier id is {}"; - - private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION = - "failed to update Interface Operation on component instance {}"; + private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION = "failed to update Interface Operation on component instance {}"; private static final String UPDATE_INTERFACE_OPERATION = "Update Interface Operation on Component Instance"; - private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR = - "Failed to update Interface Operation with an error"; + private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR = "Failed to update Interface Operation with an error"; private static final String INTERFACE_OPERATION_CONTENT_INVALID = "Interface Operation content is invalid - {}"; private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}"; - private static final String INTERFACE_OPERATION_SUCCESSFULLY_UPDATED = - "Interface Operation successfully updated on component instance with id {}"; - + private static final String INTERFACE_OPERATION_SUCCESSFULLY_UPDATED = "Interface Operation successfully updated on component instance with id {}"; private final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic; @Autowired - public ComponentInterfaceOperationServlet(final UserBusinessLogic userBusinessLogic, - final ComponentInstanceBusinessLogic componentInstanceBL, - final ComponentsUtils componentsUtils, - final ServletUtils servletUtils, + public ComponentInterfaceOperationServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL, + final ComponentsUtils componentsUtils, final ServletUtils servletUtils, final ResourceImportManager resourceImportManager, final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); @@ -101,43 +93,32 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Interface Operation", method = "PUT", - summary = "Update Interface Operation on ComponentInstance", responses = { + @Operation(description = "Update Interface Operation", method = "PUT", summary = "Update Interface Operation on ComponentInstance", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), @ApiResponse(responseCode = "201", description = "Update Interface Operation"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateComponentInstanceInterfaceOperation( - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = { - ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) - @PathParam("componentType") final String componentType, - @Parameter(description = "Component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Component Instance Id") - @PathParam("componentInstanceId") String componentInstanceId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) - throws IOException { - + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); LOGGER.debug(MODIFIER_ID_IS, userId); - final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId); final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum == null) { LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType)); } - final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); if (bytes == null || bytes.length == 0) { LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } final String data = new String(bytes); - final Optional mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum); if (mappedInterfaceOperationData.isEmpty()) { LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data); @@ -145,10 +126,9 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl } final Wrapper errorWrapper = new Wrapper<>(); try { - final Optional actionResponse = componentInterfaceOperationBusinessLogic - .updateComponentInstanceInterfaceOperation(componentId, componentInstanceId, mappedInterfaceOperationData.get(), - componentTypeEnum, errorWrapper, true); - + final Optional actionResponse = componentInterfaceOperationBusinessLogic + .updateComponentInstanceInterfaceOperation(componentId, componentInstanceId, mappedInterfaceOperationData.get(), componentTypeEnum, + errorWrapper, true); final Response response; if (actionResponse.isEmpty()) { LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentInstanceId); @@ -157,9 +137,7 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentInstanceId); response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get()); } - return response; - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION); LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e); @@ -167,13 +145,10 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl } } - private Optional getMappedInterfaceData(final String inputJson, - final User user, - final ComponentTypeEnum componentTypeEnum) { - final Either uiComponentEither = - getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user, - UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, componentTypeEnum); + private Optional getMappedInterfaceData(final String inputJson, final User user, final ComponentTypeEnum componentTypeEnum) { + final Either uiComponentEither = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, + componentTypeEnum); return uiComponentEither.left().value().getInterfaces().values().stream().findFirst(); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServlet.java index 68d8380ed2..0e2b28529d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServlet.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import io.swagger.v3.oas.annotations.Operation; @@ -72,30 +71,22 @@ public class ComponentNodeFilterServlet extends AbstractValidationsServlet { private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.class); private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}"; private static final String MODIFIER_ID_IS = "modifier id is {}"; - private static final String FAILED_TO_PARSE_COMPONENT = "failed to parse component"; - private static final String FAILED_TO_CREATE_NODE_FILTER = "failed to create node filter"; private static final String NODE_FILTER_CREATION = "Node Filter Creation"; private static final String CREATE_NODE_FILTER_WITH_AN_ERROR = "create node filter with an error"; - private static final String FAILED_TO_UPDATE_NODE_FILTER = "failed to update node filter"; private static final String NODE_FILTER_UPDATE = "Node Filter Update"; private static final String UPDATE_NODE_FILTER_WITH_AN_ERROR = "update node filter with an error"; - private static final String FAILED_TO_DELETE_NODE_FILTER = "failed to delete node filter"; private static final String NODE_FILTER_DELETE = "Node Filter Delete"; private static final String DELETE_NODE_FILTER_WITH_AN_ERROR = "delete node filter with an error"; - - private static final String INVALID_NODE_FILTER_CONSTRAINT_TYPE = "Invalid value for NodeFilterConstraintType enum {}"; - + private static final String INVALID_NODE_FILTER_CONSTRAINT_TYPE = "Invalid value for NodeFilterConstraintType enum {}"; private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic; @Inject - public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic, - final ComponentInstanceBusinessLogic componentInstanceBL, - final ComponentsUtils componentsUtils, - final ServletUtils servletUtils, + public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL, + final ComponentsUtils componentsUtils, final ServletUtils servletUtils, final ResourceImportManager resourceImportManager, final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); @@ -106,62 +97,50 @@ public class ComponentNodeFilterServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/nodeFilter") - @Operation(description = "Add Component Filter Constraint", method = "POST", - summary = "Add Component Filter Constraint", responses = { + @Operation(description = "Add Component Filter Constraint", method = "POST", summary = "Add Component Filter Constraint", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), @ApiResponse(responseCode = "201", description = "Create Component Filter"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response addComponentFilterConstraint( - @Parameter(description = "UIConstraint data", required = true) String constraintData, - @Parameter(description = "Component Id") @PathParam("componentId") String componentId, - @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = { - ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, - @Parameter(description = "Constraint type. Valid values: properties / capabilities", - schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME, - NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) - @PathParam("constraintType") final String constraintType, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response addComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = { + NodeFilterConstraintType.PROPERTIES_PARAM_NAME, + NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); LOGGER.debug(MODIFIER_ID_IS, userId); final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId); - final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); try { - final Optional convertResponse = componentsUtils - .parseToConstraint(constraintData, userModifier, componentTypeEnum); + final Optional convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum); if (convertResponse.isEmpty()) { LOGGER.error(FAILED_TO_PARSE_COMPONENT); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - final Optional nodeFilterConstraintType = - NodeFilterConstraintType.parse(constraintType); + final Optional nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType); if (nodeFilterConstraintType.isEmpty()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, - INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType)); + return buildErrorResponse( + getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType)); } final UIConstraint uiConstraint = convertResponse.get(); final String constraint = new ConstraintConvertor().convert(uiConstraint); final Optional actionResponse = componentNodeFilterBusinessLogic - .addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD, - uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum, - nodeFilterConstraintType.get(), + .addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD, uiConstraint.getServicePropertyName(), + constraint, true, componentTypeEnum, nodeFilterConstraintType.get(), StringUtils.isEmpty(uiConstraint.getCapabilityName()) ? "" : uiConstraint.getCapabilityName()); - if (actionResponse.isEmpty()) { LOGGER.error(FAILED_TO_CREATE_NODE_FILTER); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), new NodeFilterConverter().convertToUi(actionResponse.get())); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION); LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e); @@ -173,60 +152,49 @@ public class ComponentNodeFilterServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{constraintIndex}/nodeFilter") - @Operation(description = "Update Component Filter Constraint", method = "PUT", - summary = "Update Component Filter Constraint", responses = { + @Operation(description = "Update Component Filter Constraint", method = "PUT", summary = "Update Component Filter Constraint", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), @ApiResponse(responseCode = "201", description = "Create Component Filter"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateComponentFilterConstraint( - @Parameter(description = "UIConstraint data", required = true) String constraintData, - @Parameter(description = "Component Id") @PathParam("componentId") String componentId, - @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = { - ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, - @Parameter(description = "Constraint type. Valid values: properties / capabilities", - schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME, - NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) - @PathParam("constraintType") final String constraintType, - @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response updateComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = { + NodeFilterConstraintType.PROPERTIES_PARAM_NAME, + NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType, + @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); LOGGER.debug(MODIFIER_ID_IS, userId); final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId); - try { - final Optional nodeFilterConstraintTypeOptional = - NodeFilterConstraintType.parse(constraintType); + final Optional nodeFilterConstraintTypeOptional = NodeFilterConstraintType.parse(constraintType); if (nodeFilterConstraintTypeOptional.isEmpty()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, - INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType)); + return buildErrorResponse( + getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType)); } - final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - final Optional convertResponse = componentsUtils - .parseToConstraint(constraintData, userModifier, componentTypeEnum); + final Optional convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum); if (convertResponse.isEmpty()) { LOGGER.error(FAILED_TO_PARSE_COMPONENT); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } final NodeFilterConstraintType nodeFilterConstraintType = nodeFilterConstraintTypeOptional.get(); final Optional actionResponse = componentNodeFilterBusinessLogic - .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, convertResponse.get(), - componentTypeEnum, nodeFilterConstraintType, index); - + .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, convertResponse.get(), componentTypeEnum, nodeFilterConstraintType, + index); if (actionResponse.isEmpty()) { LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), new NodeFilterConverter().convertToUi(actionResponse.get())); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE); LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e); @@ -238,56 +206,45 @@ public class ComponentNodeFilterServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("{constraintIndex}/nodeFilter") - @Operation(description = "Delete Component Filter Constraint", method = "Delete", - summary = "Delete Component Filter Constraint", responses = { + @Operation(description = "Delete Component Filter Constraint", method = "Delete", summary = "Delete Component Filter Constraint", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), @ApiResponse(responseCode = "201", description = "Delete Component Filter Constraint"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteComponentFilterConstraint( - @Parameter(description = "Component Id") @PathParam("componentId") String componentId, - @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, - @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = { - ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, - @Parameter(description = "Constraint type. Valid values: properties / capabilities", - schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME, - NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) - @PathParam("constraintType") final String constraintType, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response deleteComponentFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, + @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = { + NodeFilterConstraintType.PROPERTIES_PARAM_NAME, + NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); LOGGER.debug(MODIFIER_ID_IS, userId); componentNodeFilterBusinessLogic.validateUser(userId); - try { - final Optional nodeFilterConstraintType = - NodeFilterConstraintType.parse(constraintType); + final Optional nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType); if (nodeFilterConstraintType.isEmpty()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, - INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType)); + return buildErrorResponse( + getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType)); } final Optional actionResponse = componentNodeFilterBusinessLogic - .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.DELETE, - null, index, true, ComponentTypeEnum.findByParamName(componentType), - nodeFilterConstraintType.get()); - + .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.DELETE, null, index, true, + ComponentTypeEnum.findByParamName(componentType), nodeFilterConstraintType.get()); if (actionResponse.isEmpty()) { LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), new NodeFilterConverter().convertToUi(actionResponse.get())); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE); LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java index fcca3394a0..9ff155f6da 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -28,6 +27,23 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.List; +import java.util.Map; +import javax.inject.Inject; +import javax.inject.Singleton; +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.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; @@ -48,24 +64,6 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -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; -import java.util.Map; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Tags({@Tag(name = "SDC Internal APIs")}) @@ -73,43 +71,36 @@ import java.util.Map; @Singleton public class ComponentPropertyServlet extends BeGenericServlet { - private final PropertyBusinessLogic propertyBusinessLogic; - private final ApplicationDataTypeCache applicationDataTypeCache; - - @Inject - public ComponentPropertyServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - ApplicationDataTypeCache applicationDataTypeCache, - PropertyBusinessLogic propertyBusinessLogic) { - super(userBusinessLogic, componentsUtils); - this.applicationDataTypeCache = applicationDataTypeCache; - this.propertyBusinessLogic = propertyBusinessLogic; - } - - private static final Logger log = LoggerFactory.getLogger(ComponentPropertyServlet.class); - private static final String CREATE_PROPERTY = "Create Property"; - private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}"; - private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ComponentPropertyServlet.class.getName()); - + private static final Logger log = LoggerFactory.getLogger(ComponentPropertyServlet.class); + private static final String CREATE_PROPERTY = "Create Property"; + private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}"; + private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ComponentPropertyServlet.class.getName()); + private final PropertyBusinessLogic propertyBusinessLogic; + private final ApplicationDataTypeCache applicationDataTypeCache; + + @Inject + public ComponentPropertyServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + ApplicationDataTypeCache applicationDataTypeCache, PropertyBusinessLogic propertyBusinessLogic) { + super(userBusinessLogic, componentsUtils); + this.applicationDataTypeCache = applicationDataTypeCache; + this.propertyBusinessLogic = propertyBusinessLogic; + } @POST @Path("services/{serviceId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Service Property", method = "POST", summary = "Returns created service property", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Service property created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Service property already exist")}) + @Operation(description = "Create Service Property", method = "POST", summary = "Returns created service property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Service property created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Service property already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createPropertyInService( - @Parameter(description = "service id to update with new property", - required = true) @PathParam("serviceId") final String serviceId, - @Parameter(description = "Service property to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "Service property to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return createProperty(serviceId, data, request, userId); } @@ -117,41 +108,34 @@ public class ComponentPropertyServlet extends BeGenericServlet { @Path("resources/{resourceId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Resource Property", method = "POST", summary = "Returns created service property", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource property created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Resource property already exist")}) + @Operation(description = "Create Resource Property", method = "POST", summary = "Returns created service property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource property created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Resource property already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createPropertyInResource( - @Parameter(description = "Resource id to update with new property", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "Resource property to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "Resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "Resource property to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return createProperty(resourceId, data, request, userId); } - @GET @Path("services/{serviceId}/properties/{propertyId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Service Property", method = "GET", summary = "Returns property of service", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "property"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Service property not found")}) + @Operation(description = "Get Service Property", method = "GET", summary = "Returns property of service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "property"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Service property not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getPropertyInService( - @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId, - @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return getProperty(serviceId, propertyId, request, userId); } @@ -159,20 +143,16 @@ public class ComponentPropertyServlet extends BeGenericServlet { @Path("resources/{resourceId}/properties/{propertyId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property of resource", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "property"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Resource property not found")}) + @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property of resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "property"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Resource property not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getPropertyInResource( - @Parameter(description = "resource id of property", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return getProperty(resourceId, propertyId, request, userId); } @@ -180,19 +160,15 @@ public class ComponentPropertyServlet extends BeGenericServlet { @Path("services/{serviceId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Service Property", method = "GET", summary = "Returns property list of service", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "property"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Service property not found")}) + @Operation(description = "Get Service Property", method = "GET", summary = "Returns property list of service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "property"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Service property not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getPropertyListInService( - @Parameter(description = "service id of property", - required = true) @PathParam("serviceId") final String serviceId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return getPropertyList(serviceId, request, userId); } @@ -200,19 +176,15 @@ public class ComponentPropertyServlet extends BeGenericServlet { @Path("resources/{resourceId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property list of resource", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "property"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Resource property not found")}) + @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property list of resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "property"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Resource property not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getPropertyListInResource( - @Parameter(description = "resource id of property", - required = true) @PathParam("resourceId") final String resourceId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return getPropertyList(resourceId, request, userId); } @@ -220,21 +192,17 @@ public class ComponentPropertyServlet extends BeGenericServlet { @Path("services/{serviceId}/properties/{propertyId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete Service Property", method = "DELETE", summary = "Returns deleted property", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "204", description = "deleted property"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Service property not found")}) + @Operation(description = "Delete Service Property", method = "DELETE", summary = "Returns deleted property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "204", description = "deleted property"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Service property not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deletePropertyInService( - @Parameter(description = "service id of property", - required = true) @PathParam("serviceId") final String serviceId, - @Parameter(description = "Property id to delete", - required = true) @PathParam("propertyId") final String propertyId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return deleteProperty(serviceId, propertyId, request, userId); } @@ -242,21 +210,17 @@ public class ComponentPropertyServlet extends BeGenericServlet { @Path("resources/{resourceId}/properties/{propertyId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete Resource Property", method = "DELETE", summary = "Returns deleted property", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "204", description = "deleted property"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Resource property not found")}) + @Operation(description = "Delete Resource Property", method = "DELETE", summary = "Returns deleted property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "204", description = "deleted property"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Resource property not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deletePropertyInResource( - @Parameter(description = "resource id of property", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "Property id to delete", - required = true) @PathParam("propertyId") final String propertyId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return deleteProperty(resourceId, propertyId, request, userId); } @@ -264,19 +228,16 @@ public class ComponentPropertyServlet extends BeGenericServlet { @Path("services/{serviceId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Service Property", method = "PUT", summary = "Returns updated property", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Service property updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Service Property", method = "PUT", summary = "Returns updated property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Service property updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updatePropertyInService( - @Parameter(description = "service id to update with new property", - required = true) @PathParam("serviceId") final String serviceId, - @Parameter(description = "Service property to update", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @Parameter(description = "Service property to update", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return updateProperty(serviceId, data, request, userId); } @@ -284,208 +245,163 @@ public class ComponentPropertyServlet extends BeGenericServlet { @Path("resources/{resourceId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Resource Property", method = "PUT", summary = "Returns updated property", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource property updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Resource Property", method = "PUT", summary = "Returns updated property", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource property updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updatePropertyInResource( - @Parameter(description = "resource id to update with new property", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "Resource property to update", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return updateProperty(resourceId, data, request, userId); - } - - private Response createProperty(String componentId, String data, HttpServletRequest request,String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, StatusCode.STARTED,"CREATE_PROPERTIES by user {} ", userId); - - try{ - Either, ActionStatus> propertyDefinition = - getPropertyModel(componentId, data); - if (propertyDefinition.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertyDefinition.right().value()); - return buildErrorResponse(responseFormat); - } - - Map properties = propertyDefinition.left().value(); - if (properties == null || properties.size() != 1) { - log.info("Property content is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - - Map.Entry entry = properties.entrySet().iterator().next(); - PropertyDefinition newPropertyDefinition = entry.getValue(); - newPropertyDefinition.setParentUniqueId(componentId); - String propertyName = newPropertyDefinition.getName(); - - Either, ResponseFormat> addPropertyEither = - propertyBusinessLogic.addPropertyToComponent(componentId, propertyName, newPropertyDefinition, userId); - - if(addPropertyEither.isRight()) { - return buildErrorResponse(addPropertyEither.right().value()); - } - - loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, StatusCode.COMPLETE,"CREATE_PROPERTIES by user {} ", userId); - return buildOkResponse(newPropertyDefinition); - - } 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); + @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "Resource property to update", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return updateProperty(resourceId, data, request, userId); } - } - - private Response updateProperty(String componentId, String data, HttpServletRequest request, String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED,"UPDATE_PROPERTIES by user {} ", userId); + private Response createProperty(String componentId, String data, HttpServletRequest request, String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, StatusCode.STARTED, "CREATE_PROPERTIES by user {} ", userId); + try { + Either, ActionStatus> propertyDefinition = getPropertyModel(componentId, data); + if (propertyDefinition.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertyDefinition.right().value()); + return buildErrorResponse(responseFormat); + } + Map properties = propertyDefinition.left().value(); + if (properties == null || properties.size() != 1) { + log.info("Property content is invalid - {}", data); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return buildErrorResponse(responseFormat); + } + Map.Entry entry = properties.entrySet().iterator().next(); + PropertyDefinition newPropertyDefinition = entry.getValue(); + newPropertyDefinition.setParentUniqueId(componentId); + String propertyName = newPropertyDefinition.getName(); + Either, ResponseFormat> addPropertyEither = propertyBusinessLogic + .addPropertyToComponent(componentId, propertyName, newPropertyDefinition, userId); + if (addPropertyEither.isRight()) { + return buildErrorResponse(addPropertyEither.right().value()); + } + loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, StatusCode.COMPLETE, "CREATE_PROPERTIES by user {} ", userId); + return buildOkResponse(newPropertyDefinition); + } 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 modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); + private Response updateProperty(String componentId, String data, HttpServletRequest request, String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED, "UPDATE_PROPERTIES by user {} ", userId); + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); // - try { - // convert json to PropertyDefinition - - Either, ActionStatus> propertiesListEither = - getPropertiesListForUpdate(data); - if (propertiesListEither.isRight()) { - ResponseFormat responseFormat = - getComponentsUtils().getResponseFormat(propertiesListEither.right().value()); - return buildErrorResponse(responseFormat); - } - Map properties = propertiesListEither.left().value(); - if (properties == null) { - log.info("Property content is invalid - {}", data); - ResponseFormat responseFormat = - getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - - //Validate value and Constraint of property - Either constraintValidatorResponse = - PropertyValueConstraintValidationUtil.getInstance(). - validatePropertyConstraints(properties.values(), applicationDataTypeCache); - if (constraintValidatorResponse.isRight()) { - log.error("Failed validation value and constraint of property: {}", - constraintValidatorResponse.right().value()); - return buildErrorResponse(constraintValidatorResponse.right().value()); - } - - // update property - - for(PropertyDefinition propertyDefinition : properties.values()) { - Either, ResponseFormat> status = - propertyBusinessLogic.updateComponentProperty( - componentId, propertyDefinition.getUniqueId(), propertyDefinition, userId); - if (status.isRight()) { - log.info("Failed to update Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); + try { + // convert json to PropertyDefinition + Either, ActionStatus> propertiesListEither = getPropertiesListForUpdate(data); + if (propertiesListEither.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertiesListEither.right().value()); + return buildErrorResponse(responseFormat); + } + Map properties = propertiesListEither.left().value(); + if (properties == null) { + log.info("Property content is invalid - {}", data); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return buildErrorResponse(responseFormat); + } + //Validate value and Constraint of property + Either constraintValidatorResponse = PropertyValueConstraintValidationUtil.getInstance() + .validatePropertyConstraints(properties.values(), applicationDataTypeCache); + if (constraintValidatorResponse.isRight()) { + log.error("Failed validation value and constraint of property: {}", constraintValidatorResponse.right().value()); + return buildErrorResponse(constraintValidatorResponse.right().value()); + } + // update property + for (PropertyDefinition propertyDefinition : properties.values()) { + Either, ResponseFormat> status = propertyBusinessLogic + .updateComponentProperty(componentId, propertyDefinition.getUniqueId(), propertyDefinition, 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 updatedPropertyDefinition = property.getValue(); + log.debug("Property id {} updated successfully ", updatedPropertyDefinition.getUniqueId()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "UPDATE_PROPERTIES by user {} ", userId); + return buildOkResponse(responseFormat, properties); + } 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); } - EntryData property = status.left().value(); - PropertyDefinition updatedPropertyDefinition = property.getValue(); - - log.debug("Property id {} updated successfully ", updatedPropertyDefinition.getUniqueId()); - } - - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE,"UPDATE_PROPERTIES by user {} ", userId); - return buildOkResponse(responseFormat, properties); - - } 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 Response getProperty(String componentId, String propertyId, HttpServletRequest request, String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug(DEBUG_MESSAGE, url, userId); - try { - Either, ResponseFormat> retrievedPropertyEither = - propertyBusinessLogic.getComponentProperty(componentId, propertyId, userId); - - if(retrievedPropertyEither.isRight()) { - return buildErrorResponse(retrievedPropertyEither.right().value()); - } - - return buildOkResponse(retrievedPropertyEither.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY); - log.debug("get property failed with exception", e); - ResponseFormat responseFormat = - getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); + private Response getProperty(String componentId, String propertyId, HttpServletRequest request, String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(DEBUG_MESSAGE, url, userId); + try { + Either, ResponseFormat> retrievedPropertyEither = propertyBusinessLogic + .getComponentProperty(componentId, propertyId, userId); + if (retrievedPropertyEither.isRight()) { + return buildErrorResponse(retrievedPropertyEither.right().value()); + } + return buildOkResponse(retrievedPropertyEither.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY); + log.debug("get property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } } - } - private Response getPropertyList(String componentId, HttpServletRequest request, String userId) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug(DEBUG_MESSAGE, url, userId); - try { - Either, ResponseFormat> propertiesListEither = - propertyBusinessLogic.getPropertiesList(componentId, userId); - - if(propertiesListEither.isRight()) { - return buildErrorResponse(propertiesListEither.right().value()); - } - - return buildOkResponse(propertiesListEither.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY); - log.debug("get property failed with exception", e); - ResponseFormat responseFormat = - getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); + private Response getPropertyList(String componentId, HttpServletRequest request, String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(DEBUG_MESSAGE, url, userId); + try { + Either, ResponseFormat> propertiesListEither = propertyBusinessLogic.getPropertiesList(componentId, userId); + if (propertiesListEither.isRight()) { + return buildErrorResponse(propertiesListEither.right().value()); + } + return buildOkResponse(propertiesListEither.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY); + log.debug("get property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } } - } - private Response deleteProperty(String componentId, String propertyId, HttpServletRequest request, String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug(DEBUG_MESSAGE, url, userId); - - try { - - // delete the property - Either, ResponseFormat> status = - propertyBusinessLogic.deletePropertyFromComponent(componentId, propertyId, userId); - if (status.isRight()) { - log.debug("Failed to delete Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - Map.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); + private Response deleteProperty(String componentId, String propertyId, HttpServletRequest request, String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(DEBUG_MESSAGE, url, userId); + try { + // delete the property + Either, ResponseFormat> status = propertyBusinessLogic + .deletePropertyFromComponent(componentId, propertyId, userId); + if (status.isRight()) { + log.debug("Failed to delete Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + Map.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); + } } - } - } 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 6c5d603225..28ebfd42d1 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 @@ -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. @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; +import static org.openecomp.sdc.common.util.GeneralUtility.getCategorizedComponents; + import com.jcabi.aspects.Loggable; import fj.data.Either; import io.swagger.v3.oas.annotations.Operation; @@ -32,6 +33,24 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import javax.inject.Inject; +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 org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider; @@ -59,49 +78,23 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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.io.IOException; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - -import static org.openecomp.sdc.common.util.GeneralUtility.getCategorizedComponents; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Tags({@Tag(name = "SDC Internal APIs")}) @Servers({@Server(url = "/sdc2/rest")}) @Controller public class ComponentServlet extends BeGenericServlet { - private static final String GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION = "getCertifiedNotAbstractComponents failed with exception"; - - private static final String GET_CERTIFIED_NON_ABSTRACT = "Get Certified Non Abstract"; - - private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}"; - - private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; - - private static final Logger log = Logger.getLogger(ComponentServlet.class); + private static final String GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION = "getCertifiedNotAbstractComponents failed with exception"; + private static final String GET_CERTIFIED_NON_ABSTRACT = "Get Certified Non Abstract"; + private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}"; + private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; + private static final Logger log = Logger.getLogger(ComponentServlet.class); private final ComponentBusinessLogicProvider componentBusinessLogicProvider; @Inject - public ComponentServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - ComponentBusinessLogicProvider componentBusinessLogicProvider) { + public ComponentServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + ComponentBusinessLogicProvider componentBusinessLogicProvider) { super(userBusinessLogic, componentsUtils); this.componentBusinessLogicProvider = componentBusinessLogicProvider; } @@ -110,21 +103,17 @@ public class ComponentServlet extends BeGenericServlet { @Path("/{componentType}/{componentUuid}/conformanceLevelValidation") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Validate Component Conformance Level", method = "GET", - summary = "Returns the result according to conformance level in BE config", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @Operation(description = "Validate Component Conformance Level", method = "GET", summary = "Returns the result according to conformance level in BE config", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { + @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { Response response; - String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum != null) { ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum); @@ -132,12 +121,12 @@ public class ComponentServlet extends BeGenericServlet { if (eitherConformanceLevel.isRight()) { response = buildErrorResponse(eitherConformanceLevel.right().value()); } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value())); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + gson.toJson(eitherConformanceLevel.left().value())); } } else { response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } - return response; } @@ -145,27 +134,23 @@ public class ComponentServlet extends BeGenericServlet { @Path("/{componentType}/{componentId}/requirmentsCapabilities") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Component Requirments And Capabilities", method = "GET", - summary = "Returns Requirements And Capabilities according to componentId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @Operation(description = "Get Component Requirments And Capabilities", method = "GET", summary = "Returns Requirements And Capabilities according to componentId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) throws IOException { + @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { Response response; - String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum != null) { try { ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum); response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - RepresentationUtils.toRepresentation(compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId))); + RepresentationUtils.toRepresentation(compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId))); } catch (IOException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId); log.debug("getRequirementAndCapabilities failed with exception", e); @@ -174,7 +159,6 @@ public class ComponentServlet extends BeGenericServlet { } else { response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } - return response; } @@ -182,43 +166,34 @@ public class ComponentServlet extends BeGenericServlet { @Path("/{componentType}/latestversion/notabstract") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Component Requirments And Capabilities", method = "GET", - summary = "Returns Requirments And Capabilities according to componentId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @Operation(description = "Get Component Requirments And Capabilities", method = "GET", summary = "Returns Requirments And Capabilities according to componentId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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) throws IOException { - + 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) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of {}", url); - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum); - log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size()); - - Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, componentUids, userId); - + Either, ResponseFormat> actionResponse = businessLogic + .getLatestVersionNotAbstractComponents(false, 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(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e); throw e; - } } @@ -226,49 +201,39 @@ public class ComponentServlet extends BeGenericServlet { @Path("/{componentType}/latestversion/notabstract") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Component Requirments And Capabilities", method = "GET", - summary = "Returns Requirments And Capabilities according to componentId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @Operation(description = "Get Component Requirments And Capabilities", method = "GET", summary = "Returns Requirments And Capabilities according to componentId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getLatestVersionNotAbstractCheckoutComponentsByBody( - @PathParam("componentType") final String componentType, @Context final HttpServletRequest request, - @QueryParam("internalComponentType") String internalComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "Consumer Object to be created", required = true) List data) throws IOException { - + public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, + @Context final HttpServletRequest request, + @QueryParam("internalComponentType") String internalComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "Consumer Object to be created", required = true) List data) + throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(GET) Start handle request of {}", url); Response response; - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum); if (log.isDebugEnabled()) { log.debug("Received componentUids size is {}", data == null ? 0 : data.size()); } - - Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, data, userId); - + Either, ResponseFormat> actionResponse = businessLogic + .getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, data, 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); - - - + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType); log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e); throw e; } - } @GET @@ -276,72 +241,69 @@ public class ComponentServlet extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Get Component uid only", method = "GET", summary = "Returns componentId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly( - @PathParam("componentType") final String componentType, @Context final HttpServletRequest request, - @QueryParam("internalComponentType") String internalComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "uid list", required = true) String data) throws IOException { - + public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, + @Context final HttpServletRequest request, + @QueryParam("internalComponentType") String internalComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "uid list", required = true) String data) + throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of {}", url); try { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum); - - Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId); + 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()); } - List uiLeftPaletteComponents = getComponentsUtils().convertComponentToUiLeftPaletteComponentObject(actionResponse.left().value()); + List uiLeftPaletteComponents = getComponentsUtils() + .convertComponentToUiLeftPaletteComponentObject(actionResponse.left().value()); Map>> categorizedComponents = getCategorizedComponents(uiLeftPaletteComponents); Object components = RepresentationUtils.toRepresentation(categorizedComponents); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType); log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e); throw e; } - } @GET @Path("/{componentType}/{componentId}/componentInstances") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get Component instances", method = "GET", summary = "Returns component instances", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @Operation(description = "Get Component instances", method = "GET", summary = "Returns component instances", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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, - @Parameter(description = "uid" + " " + "list", required = true) String data) throws IOException { - + 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, + @Parameter(description = "uid" + " " + "list", required = true) String data) + throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(GET) Start handle request of {}", url); try { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum); - - Either, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, userId); + Either, ResponseFormat> actionResponse = businessLogic + .getComponentInstancesFilteredByPropertiesAndInputs(componentId, userId); 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); @@ -349,11 +311,9 @@ public class ComponentServlet extends BeGenericServlet { } } - - /** - * 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. + * 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 @@ -362,48 +322,40 @@ public class ComponentServlet extends BeGenericServlet { * @param userId * @return */ - - @GET @Path("/{componentType}/{componentId}/filteredDataByParams") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Resource found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found")}) + @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Resource found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found")}) @ResponseView(mixin = {GroupCompositionMixin.class, PolicyCompositionMixin.class}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) throws IOException { - + @PathParam("componentId") final String componentId, + @QueryParam("include") final List dataParamsToReturn, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug(START_HANDLE_REQUEST_OF , url); - + log.debug(START_HANDLE_REQUEST_OF, url); // get modifier id User modifier = new User(); modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - + log.debug("modifier id is {}", userId); try { String resourceIdLower = componentId.toLowerCase(); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum); - log.trace("get component with id {} filtered by ui params", componentId); - Either actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn); - + Either actionResponse = businessLogic + .getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn); if (actionResponse.isRight()) { log.debug("failed to get component data filtered by ui params"); return buildErrorResponse(actionResponse.right().value()); } RepresentationUtils.toRepresentation(actionResponse.left().value()); return buildOkResponse(actionResponse.left().value()); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params"); log.debug("get resource failed with exception", e); @@ -411,32 +363,24 @@ public class ComponentServlet extends BeGenericServlet { } } - @GET @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation( - description = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", - method = "GET", - summary = "Returns properties belonging to component instances of specific component by name and optionally resource type", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Map.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @Operation(description = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", method = "GET", summary = "Returns properties belonging to component instances of specific component by name and optionally resource type", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Map.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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) throws IOException { - + 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) throws IOException { User user = new User(); user.setUserId(userId); - log.debug("User Id is {}" , userId); + log.debug("User Id is {}", userId); Response response; try { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); @@ -445,17 +389,17 @@ public class ComponentServlet extends BeGenericServlet { List propertyNameFragments = new ArrayList<>(); propertyNameFragments.add(propertyNameFragment); filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments); - if(CollectionUtils.isNotEmpty(resourceTypes)){ + if (CollectionUtils.isNotEmpty(resourceTypes)) { filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes); } - Either>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId); + 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); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentSubstitutionFilterServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentSubstitutionFilterServlet.java index 4a44c202f3..f12fbd761d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentSubstitutionFilterServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentSubstitutionFilterServlet.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import io.swagger.v3.oas.annotations.Operation; @@ -75,26 +74,20 @@ public class ComponentSubstitutionFilterServlet extends AbstractValidationsServl private static final String MODIFIER_ID_IS = "Modifier id is {}"; private static final String FAILED_TO_PARSE_COMPONENT = "Failed to parse component"; private static final String INVALID_CONSTRAINTYPE_ENUM = "Invalid value for NodeFilterConstraintType enum %s"; - private static final String FAILED_TO_ADD_SUBSTITUTION_FILTER = "Failed to add substitution filter"; private static final String ADD_SUBSTITUTION_FILTER = "Add Substitution Filter"; private static final String ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Add substitution filter with an error"; - private static final String FAILED_TO_UPDATE_SUBSTITUTION_FILTER = "Failed to update substitution filter"; private static final String SUBSTITUTION_FILTER_UPDATE = "Substitution Filter Update"; private static final String UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Update substitution filter with an error {}"; - private static final String FAILED_TO_DELETE_SUBSTITUTION_FILTER = "Failed to delete substitution filter"; private static final String SUBSTITUTION_FILTER_DELETE = "Substitution Filter Delete"; private static final String DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Delete substitution filter with an error"; - private final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic; @Inject - public ComponentSubstitutionFilterServlet(final UserBusinessLogic userBusinessLogic, - final ComponentInstanceBusinessLogic componentInstanceBL, - final ComponentsUtils componentsUtils, - final ServletUtils servletUtils, + public ComponentSubstitutionFilterServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL, + final ComponentsUtils componentsUtils, final ServletUtils servletUtils, final ResourceImportManager resourceImportManager, final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); @@ -104,62 +97,46 @@ public class ComponentSubstitutionFilterServlet extends AbstractValidationsServl @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Add Component Substitution Filter Constraint", method = "POST", - summary = "Add Component Substitution Filter Constraint", responses = { + @Operation(description = "Add Component Substitution Filter Constraint", method = "POST", summary = "Add Component Substitution Filter Constraint", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), @ApiResponse(responseCode = "201", description = "Add Substitution Filter Constraint"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response addSubstitutionFilter( - @Parameter(description = "UIConstraint data", required = true) String constraintData, - @Parameter(description = "Component Id") @PathParam("componentId") String componentId, - @Parameter(description = "valid value: resources / services", - schema = @Schema(allowableValues = { - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, - @Parameter(description = "Constraint type. Valid values: properties / capabilities", - schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME, - NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) - @PathParam("constraintType") final String constraintType, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response addSubstitutionFilter(@Parameter(description = "UIConstraint data", required = true) String constraintData, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = { + NodeFilterConstraintType.PROPERTIES_PARAM_NAME, + NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); LOGGER.debug(MODIFIER_ID_IS, userId); final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId); - final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); try { - final Optional convertResponse = componentsUtils - .parseToConstraint(constraintData, userModifier, componentTypeEnum); + final Optional convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum); if (convertResponse.isEmpty()) { LOGGER.error(FAILED_TO_PARSE_COMPONENT); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - final UIConstraint uiConstraint = convertResponse.get(); final String constraint = new ConstraintConvertor().convert(uiConstraint); - - final Optional nodeFilterConstraintType = - NodeFilterConstraintType.parse(constraintType); + final Optional nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType); if (nodeFilterConstraintType.isEmpty()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, - INVALID_CONSTRAINTYPE_ENUM, constraintType)); + return buildErrorResponse( + getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType)); } - final Optional actionResponse = componentSubstitutionFilterBusinessLogic - .addSubstitutionFilter(componentId.toLowerCase(), - uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum); - + .addSubstitutionFilter(componentId.toLowerCase(), uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum); if (actionResponse.isEmpty()) { LOGGER.error(FAILED_TO_ADD_SUBSTITUTION_FILTER); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } final UINodeFilter uiFilter = new SubstitutionFilterConverter().convertToUi(actionResponse.get()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiFilter); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(ADD_SUBSTITUTION_FILTER); LOGGER.error(ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR, e); @@ -170,60 +147,46 @@ public class ComponentSubstitutionFilterServlet extends AbstractValidationsServl @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", - summary = "Update Component Substitution Filter Constraint", responses = { + @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", summary = "Update Component Substitution Filter Constraint", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateSubstitutionFilter( - @Parameter(description = "UIConstraint data", required = true) String constraintData, - @Parameter(description = "Component Id") @PathParam("componentId") String componentId, - @Parameter(description = "valid value: resources / services", - schema = @Schema(allowableValues = { - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, - @Parameter(description = "Constraint type. Valid values: properties / capabilities", - schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME, - NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) - @PathParam("constraintType") final String constraintType, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response updateSubstitutionFilter(@Parameter(description = "UIConstraint data", required = true) String constraintData, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = { + NodeFilterConstraintType.PROPERTIES_PARAM_NAME, + NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); LOGGER.debug(MODIFIER_ID_IS, userId); final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId); - try { final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - final List uiConstraints = componentsUtils - .validateAndParseConstraint(componentTypeEnum, constraintData, userModifier); + final List uiConstraints = componentsUtils.validateAndParseConstraint(componentTypeEnum, constraintData, userModifier); if (CollectionUtils.isEmpty(uiConstraints)) { - LOGGER.error("Failed to Parse Constraint data {} when executing {} ", - constraintData, SUBSTITUTION_FILTER_UPDATE); - return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, - "Failed to parse constraint data")); + LOGGER.error("Failed to Parse Constraint data {} when executing {} ", constraintData, SUBSTITUTION_FILTER_UPDATE); + return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to parse constraint data")); } - final List constraints = new ConstraintConvertor().convertToList(uiConstraints); - final Optional nodeFilterConstraintType = - NodeFilterConstraintType.parse(constraintType); + final Optional nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType); if (!nodeFilterConstraintType.isPresent()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, - INVALID_CONSTRAINTYPE_ENUM, constraintType)); + return buildErrorResponse( + getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType)); } final Optional actionResponse = componentSubstitutionFilterBusinessLogic - .updateSubstitutionFilter(componentId.toLowerCase(), constraints, - true, componentTypeEnum); - + .updateSubstitutionFilter(componentId.toLowerCase(), constraints, true, componentTypeEnum); if (!actionResponse.isPresent()) { LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), new SubstitutionFilterConverter().convertToUi(actionResponse.get())); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE); LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e); @@ -235,55 +198,43 @@ public class ComponentSubstitutionFilterServlet extends AbstractValidationsServl @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{constraintIndex}") - @Operation(description = "Delete Component Substitution Filter Constraint", method = "Delete", - summary = "Delete Component Substitution Filter Constraint", responses = { + @Operation(description = "Delete Component Substitution Filter Constraint", method = "Delete", summary = "Delete Component Substitution Filter Constraint", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), @ApiResponse(responseCode = "201", description = "Delete Substitution Filter Constraint"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteSubstitutionFilterConstraint( - @Parameter(description = "Component Id") @PathParam("componentId") String componentId, - @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index, - @Parameter(description = "valid value: resources / services", - schema = @Schema(allowableValues = { - ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, - @Parameter(description = "Constraint type. Valid values: properties / capabilities", - schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME, - NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) - @PathParam("constraintType") final String constraintType, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response deleteSubstitutionFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index, + @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = { + ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = { + NodeFilterConstraintType.PROPERTIES_PARAM_NAME, + NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); LOGGER.debug(MODIFIER_ID_IS, userId); componentSubstitutionFilterBusinessLogic.validateUser(userId); - - final Optional nodeFilterConstraintType = - NodeFilterConstraintType.parse(constraintType); - if (!nodeFilterConstraintType.isPresent()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, - INVALID_CONSTRAINTYPE_ENUM, constraintType)); - } - + final Optional nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType); + if (!nodeFilterConstraintType.isPresent()) { + return buildErrorResponse( + getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType)); + } try { final Optional actionResponse = componentSubstitutionFilterBusinessLogic .deleteSubstitutionFilter(componentId.toLowerCase(), index, true, ComponentTypeEnum.findByParamName(componentType)); - if (!actionResponse.isPresent()) { LOGGER.debug(FAILED_TO_DELETE_SUBSTITUTION_FILTER); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), new SubstitutionFilterConverter().convertToUi(actionResponse.get())); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_DELETE); LOGGER.debug(DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR, 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 24eb5314f7..9249d21dc3 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -25,14 +24,6 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdc.be.components.impl.aaf.AafPermission; -import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.servlets.BasicServlet; - import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; @@ -44,6 +35,13 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import org.openecomp.sdc.be.components.impl.aaf.AafPermission; +import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.servlets.BasicServlet; /** * Root resource (exposed at "/" path) @@ -61,28 +59,19 @@ public class ConfigMgrServlet extends BasicServlet { @Produces(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) { - String result = null; - ServletContext context = request.getSession().getServletContext(); - ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); - 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); - result = gson.toJson(configuration); - } } - return result; - } @POST @@ -91,11 +80,8 @@ public class ConfigMgrServlet extends BasicServlet { @Consumes(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public String setConfig1(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); - return "ok"; - } @POST @@ -104,9 +90,7 @@ public class ConfigMgrServlet extends BasicServlet { @Consumes(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public void setConfig2(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); - } @PUT @@ -115,11 +99,8 @@ public class ConfigMgrServlet extends BasicServlet { @Consumes(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public String setConfig3(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); - return "ok"; - } @PUT @@ -128,9 +109,6 @@ public class ConfigMgrServlet extends BasicServlet { @Consumes(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public void setConfig4(@Context final HttpServletRequest request, Configuration 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 86a8a2d352..1c90ea0747 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -29,14 +28,6 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdc.be.components.impl.aaf.AafPermission; -import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.servlets.BasicServlet; - import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; @@ -44,6 +35,13 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import org.openecomp.sdc.be.components.impl.aaf.AafPermission; +import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.servlets.BasicServlet; /** * Root resource (exposed at "/" path) @@ -61,33 +59,23 @@ public class ConfigServlet extends BasicServlet { @Produces(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) @Operation(description = "Retrieve configuration", method = "GET", responses = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = String.class))) - }) + @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = String.class)))}) public String getConfig(@Context final HttpServletRequest request) { - String result = null; - ServletContext context = request.getSession().getServletContext(); - 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); - result = gson.toJson(configuration); - } else { log.warn("Source Configuration object was not initialized in the context."); } - 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 f3d18602bd..4b31cb1371 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.google.gson.Gson; @@ -33,18 +32,6 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; -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.ConsumerDefinition; -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.log.wrappers.Logger; -import org.openecomp.sdc.exception.ResponseFormat; - import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletContext; @@ -60,6 +47,17 @@ 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.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; +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.ConsumerDefinition; +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.log.wrappers.Logger; +import org.openecomp.sdc.exception.ResponseFormat; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/consumers") @@ -69,14 +67,12 @@ import javax.ws.rs.core.Response; public class ConsumerServlet extends BeGenericServlet { private static final String MODIFIER_ID_IS = "modifier id is {}"; - private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; - private static final Logger log = Logger.getLogger(ConsumerServlet.class); + private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; + private static final Logger log = Logger.getLogger(ConsumerServlet.class); private final ConsumerBusinessLogic businessLogic; - @Inject - public ConsumerServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - ConsumerBusinessLogic businessLogic) { + @Inject + public ConsumerServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, ConsumerBusinessLogic businessLogic) { super(userBusinessLogic, componentsUtils); this.businessLogic = businessLogic; } @@ -84,49 +80,38 @@ public class ConsumerServlet extends BeGenericServlet { @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Consumer credentials", method = "POST", - summary = "Returns created ECOMP consumer credentials", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Consumer credentials created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Consumer credentials", method = "POST", summary = "Returns created ECOMP consumer credentials", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Consumer credentials created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) public Response createConsumer(@Parameter(description = "Consumer Object to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @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 { - 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()); } - ConsumerDefinition consumer = convertionResponse.left().value(); - Either actionResult = businessLogic.createConsumer(modifier, consumer); - if (actionResult.isRight()) { log.debug("failed to create Consumer"); return buildErrorResponse(actionResult.right().value()); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value()); - } 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); - } } @@ -134,33 +119,25 @@ public class ConsumerServlet extends BeGenericServlet { @Path("/{consumerId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Consumer", method = "GET", summary = "Returns consumer according to ConsumerID", - responses = {@ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))), - @ApiResponse(responseCode = "200", description = "Consumer found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Consumer not found")}) - public Response getConsumer(@PathParam("consumerId") final String consumerId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Operation(description = "Retrieve Consumer", method = "GET", summary = "Returns consumer according to ConsumerID", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))), + @ApiResponse(responseCode = "200", description = "Consumer found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "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); - try { Either actionResponse = businessLogic.getConsumer(consumerId, modifier); - if (actionResponse.isRight()) { log.debug("failed to get consumer"); return buildErrorResponse(actionResponse.right().value()); } 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); @@ -172,31 +149,25 @@ public class ConsumerServlet extends BeGenericServlet { @Path("/{consumerId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Deletes Consumer", method = "DELETE", - summary = "Returns deleted consumer according to ConsumerID", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))), - @ApiResponse(responseCode = "204", description = "Consumer deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Consumer not found")}) - public Response deleteConsumer(@PathParam("consumerId") final String consumerId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Operation(description = "Deletes Consumer", method = "DELETE", summary = "Returns deleted consumer according to ConsumerID", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))), + @ApiResponse(responseCode = "204", description = "Consumer deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Consumer not found")}) + public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { 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 { Either actionResponse = businessLogic.deleteConsumer(consumerId, modifier); - if (actionResponse.isRight()) { log.debug("failed to delete consumer"); return buildErrorResponse(actionResponse.right().value()); } 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); @@ -225,5 +196,4 @@ public class ConsumerServlet extends BeGenericServlet { } return Either.left(consumer); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DirectiveServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DirectiveServlet.java index adffdaf9d7..d1cee1bf6e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DirectiveServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DirectiveServlet.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import io.swagger.v3.oas.annotations.Operation; @@ -57,29 +56,23 @@ public class DirectiveServlet extends BeGenericServlet { private static final Logger LOGGER = LoggerFactory.getLogger(DirectiveServlet.class); @Inject - public DirectiveServlet(final UserBusinessLogic userAdminManager, - final ComponentsUtils componentsUtils) { + public DirectiveServlet(final UserBusinessLogic userAdminManager, final ComponentsUtils componentsUtils) { super(userAdminManager, componentsUtils); } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve all Directives values from configuration file", method = "GET", - summary = "Retrieve all Directives", responses = { + @Operation(description = "Retrieve all Directives values from configuration file", method = "GET", summary = "Retrieve all Directives", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", - description = "Returns Directive values from configuration file Ok"), - @ApiResponse(responseCode = "404", - description = "Directive not found"), + @ApiResponse(responseCode = "200", description = "Returns Directive values from configuration file Ok"), + @ApiResponse(responseCode = "404", description = "Directive not found"), @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getConfCategoriesAndVersion(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - final String url = request.getMethod() + " " + request.getRequestURI(); LOGGER.debug("Start handle request of {}", url); - final Map directivesMap = new HashMap<>(); try { final List directives = getDirectiveValues(); @@ -87,18 +80,15 @@ public class DirectiveServlet extends BeGenericServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); } directivesMap.put("directives", directives); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("SDC Failed to retrieve all Directives"); LOGGER.debug("Method getDirectiveValues failed with unexpected exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), directivesMap); } private List getDirectiveValues() { return ConfigurationManager.getConfigurationManager().getConfiguration().getDirectives(); } - } 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 46338c2986..20a1df2ac3 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,6 +30,17 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.inject.Inject; +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 org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; @@ -45,18 +55,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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; - /** * Root resource (exposed at "/" path) */ @@ -66,72 +64,61 @@ import javax.ws.rs.core.Response; @Servers({@Server(url = "/sdc2/rest")}) @Controller public class DistributionServiceServlet extends BeGenericServlet { + private static final Logger log = Logger.getLogger(DistributionServiceServlet.class); + private DistributionMonitoringBusinessLogic distributionMonitoringLogic; @Inject - public DistributionServiceServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - DistributionMonitoringBusinessLogic distributionMonitoringLogic) { + public DistributionServiceServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + DistributionMonitoringBusinessLogic distributionMonitoringLogic) { super(userBusinessLogic, componentsUtils); this.distributionMonitoringLogic = distributionMonitoringLogic; } - private DistributionMonitoringBusinessLogic distributionMonitoringLogic; - @GET @Path("/services/{serviceUUID}/distribution") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Distributions", method = "GET", - summary = "Returns list bases on the information extracted from Auditing Records according to service uuid", - responses = {@ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))), - @ApiResponse(responseCode = "200", description = "Service found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @Operation(description = "Retrieve Distributions", method = "GET", summary = "Returns list bases on the information extracted from Auditing Records according to service uuid", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))), + @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url); try { - Either actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId); - + Either actionResponse = distributionMonitoringLogic + .getListOfDistributionServiceStatus(serviceUUID, userId); if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } else { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service"); log.debug("failed to get service distribution statuses", e); throw e; } - } @GET @Path("/services/distribution/{did}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Distributions", method = "GET", - summary = "Return the list of distribution status objects", responses = {@ApiResponse( - content = @Content( - array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))), - @ApiResponse(responseCode = "200", description = "Service found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Status not found")}) + @Operation(description = "Retrieve Distributions", method = "GET", summary = "Return the list of distribution status objects", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))), + @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Status not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getListOfDistributionStatuses(@PathParam("did") final String did, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url); try { - Either actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId); - + Either actionResponse = distributionMonitoringLogic + .getListOfDistributionStatus(did, userId); if (actionResponse.isRight()) { ResponseFormat responseFormat = actionResponse.right().value(); log.debug("failed to fount statuses for did {} {}", did, responseFormat); @@ -146,7 +133,5 @@ public class DistributionServiceServlet extends BeGenericServlet { log.debug("failed to get distribution status ", e); throw e; } - } - } 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 9ea4a44acb..e0382c0885 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,6 +30,26 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.inject.Inject; +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.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; @@ -63,29 +82,7 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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 java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - @Path("/v1/") - /** * * UI oriented servlet - to return elements in specific format UI needs @@ -105,17 +102,14 @@ public class ElementServlet extends BeGenericServlet { private final ArtifactsBusinessLogic artifactsBusinessLogic; @Inject - public ElementServlet(final UserBusinessLogic userBusinessLogic, - final ComponentsUtils componentsUtils, - final ComponentsCleanBusinessLogic componentsCleanBusinessLogic, - final ElementBusinessLogic elementBusinessLogic, + public ElementServlet(final UserBusinessLogic userBusinessLogic, final ComponentsUtils componentsUtils, + final ComponentsCleanBusinessLogic componentsCleanBusinessLogic, final ElementBusinessLogic elementBusinessLogic, final ArtifactsBusinessLogic artifactsBusinessLogic) { super(userBusinessLogic, componentsUtils); this.componentsCleanBusinessLogic = componentsCleanBusinessLogic; this.elementBusinessLogic = elementBusinessLogic; this.artifactsBusinessLogic = artifactsBusinessLogic; } - /* ****************************************************************************** * NEW CATEGORIES category / \ subcategory subcategory / grouping @@ -126,29 +120,27 @@ public class ElementServlet extends BeGenericServlet { * * CATEGORIES */ + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all component categories @GET @Path("/categories/{componentType}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", - method = "GET", - summary = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Returns categories Ok"), - @ApiResponse(responseCode = "403", description = "Missing information"), - @ApiResponse(responseCode = "400", description = "Invalid component type"), - @ApiResponse(responseCode = "409", description = "Restricted operation"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @Operation(description = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", method = "GET", summary = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Returns categories Ok"), + @ApiResponse(responseCode = "403", description = "Missing information"), + @ApiResponse(responseCode = "400", description = "Invalid component type"), + @ApiResponse(responseCode = "409", description = "Restricted operation"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getComponentCategories( - @Parameter(description = "allowed values are resources / services/ products", schema = @Schema(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) { - + @Parameter(description = "allowed values are resources / services/ products", schema = @Schema(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); @@ -169,34 +161,28 @@ public class ElementServlet extends BeGenericServlet { @Path("/category/{componentType}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create new component category", method = "POST", - summary = "Create new component category", - responses = {@ApiResponse(responseCode = "201", description = "Category created"), - @ApiResponse(responseCode = "400", description = "Invalid category data"), - @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), - @ApiResponse(responseCode = "409", - description = "Category already exists / User not permitted to perform the action"), - @ApiResponse(responseCode = "500", description = "General Error")}) + @Operation(description = "Create new component category", method = "POST", summary = "Create new component category", responses = { + @ApiResponse(responseCode = "201", description = "Category created"), + @ApiResponse(responseCode = "400", description = "Invalid category data"), + @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), + @ApiResponse(responseCode = "409", description = "Category already exists / User not permitted to perform the action"), + @ApiResponse(responseCode = "500", description = "General Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createComponentCategory( - @Parameter(description = "allowed values are resources /services / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME , - ComponentTypeEnum.SERVICE_PARAM_NAME,ComponentTypeEnum.PRODUCT_PARAM_NAME}), - required = true) @PathParam(value = "componentType") final String componentType, - @Parameter(description = "Category to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @Parameter(description = "allowed values are resources /services / products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType, + @Parameter(description = "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); @@ -208,29 +194,24 @@ public class ElementServlet extends BeGenericServlet { @Path("/category/{componentType}/{categoryUniqueId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))), - @ApiResponse(responseCode = "204", description = "Category deleted"), - @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), - @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"), - @ApiResponse(responseCode = "404", description = "Category not found"), - @ApiResponse(responseCode = "500", description = "General Error")}) + @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))), + @ApiResponse(responseCode = "204", description = "Category deleted"), + @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), + @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"), + @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { - + @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); @@ -244,43 +225,34 @@ public class ElementServlet extends BeGenericServlet { * SUBCATEGORIES * */ - @POST @Path("/category/{componentType}/{categoryId}/subCategory") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create new component sub-category", method = "POST", - summary = "Create new component sub-category for existing category", - responses = {@ApiResponse(responseCode = "201", description = "Subcategory created"), - @ApiResponse(responseCode = "400", description = "Invalid subcategory data"), - @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), - @ApiResponse(responseCode = "404", description = "Parent category wasn't found"), - @ApiResponse(responseCode = "409", - description = "Subcategory already exists / User not permitted to perform the action"), - @ApiResponse(responseCode = "500", description = "General Error")}) + @Operation(description = "Create new component sub-category", method = "POST", summary = "Create new component sub-category for existing category", responses = { + @ApiResponse(responseCode = "201", description = "Subcategory created"), + @ApiResponse(responseCode = "400", description = "Invalid subcategory data"), + @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), + @ApiResponse(responseCode = "404", description = "Parent category wasn't found"), + @ApiResponse(responseCode = "409", description = "Subcategory already exists / User not permitted to perform the action"), + @ApiResponse(responseCode = "500", description = "General Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createComponentSubCategory( - @Parameter(description = "allowed values are resources / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME , - ComponentTypeEnum.PRODUCT_PARAM_NAME}), - required = true) @PathParam(value = "componentType") final String componentType, - @Parameter(description = "Parent category unique ID", - required = true) @PathParam(value = "categoryId") final String categoryId, - @Parameter(description = "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) { - + @Parameter(description = "allowed values are resources / products", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType, + @Parameter(description = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId, + @Parameter(description = "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); + 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); @@ -292,29 +264,27 @@ public class ElementServlet extends BeGenericServlet { @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))), - @ApiResponse(responseCode = "204", description = "Category deleted"), - @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), - @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"), - @ApiResponse(responseCode = "404", description = "Category not found"), - @ApiResponse(responseCode = "500", description = "General Error")}) + @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))), + @ApiResponse(responseCode = "204", description = "Category deleted"), + @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), + @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"), + @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { - + @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(subCategoryUniqueId, componentType, userId); + Either deleteSubResourceCategory = elementBL + .deleteSubCategory(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 subcategory"); log.debug("deleteComponentSubCategory failed with exception", e); @@ -329,37 +299,30 @@ public class ElementServlet extends BeGenericServlet { @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create new component grouping", method = "POST", - summary = "Create new component grouping for existing sub-category", - responses = {@ApiResponse(responseCode = "201", description = "Grouping created"), - @ApiResponse(responseCode = "400", description = "Invalid grouping data"), - @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), - @ApiResponse(responseCode = "404", description = "Parent category or subcategory were not found"), - @ApiResponse(responseCode = "409", - description = "Grouping already exists / User not permitted to perform the action"), - @ApiResponse(responseCode = "500", description = "General Error")}) + @Operation(description = "Create new component grouping", method = "POST", summary = "Create new component grouping for existing sub-category", responses = { + @ApiResponse(responseCode = "201", description = "Grouping created"), + @ApiResponse(responseCode = "400", description = "Invalid grouping data"), + @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), + @ApiResponse(responseCode = "404", description = "Parent category or subcategory were not found"), + @ApiResponse(responseCode = "409", description = "Grouping already exists / User not permitted to perform the action"), + @ApiResponse(responseCode = "500", description = "General Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createComponentGrouping( - @Parameter(description = "allowed values are products", - schema = @Schema(allowableValues = {ComponentTypeEnum.PRODUCT_PARAM_NAME}), - required = true) @PathParam(value = "componentType") final String componentType, - @Parameter(description = "Parent category unique ID", - required = true) @PathParam(value = "categoryId") final String grandParentCategoryId, - @Parameter(description = "Parent sub-category unique ID", - required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, - @Parameter(description = "Subcategory to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response createComponentGrouping(@Parameter(description = "allowed values are products", schema = @Schema(allowableValues = { + ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType, + @Parameter(description = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId, + @Parameter(description = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, + @Parameter(description = "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); + 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); @@ -371,22 +334,18 @@ public class ElementServlet extends BeGenericServlet { @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))), - @ApiResponse(responseCode = "204", description = "Category deleted"), - @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), - @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"), - @ApiResponse(responseCode = "404", description = "Category not found"), - @ApiResponse(responseCode = "500", description = "General Error")}) + @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))), + @ApiResponse(responseCode = "204", description = "Category deleted"), + @ApiResponse(responseCode = "403", description = "USER_ID header is missing"), + @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"), + @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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) { - + 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(groupingUniqueId, componentType, userId); @@ -395,31 +354,27 @@ public class ElementServlet extends BeGenericServlet { } 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); throw e; } } - ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all tags @GET @Path("/tags") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Retrieve all tags", method = "GET", summary = "Retrieve all tags", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns tags Ok"), - @ApiResponse(responseCode = "404", description = "No tags were found"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns tags Ok"), @ApiResponse(responseCode = "404", description = "No tags were found"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getTags(@Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + 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); @@ -435,25 +390,22 @@ public class ElementServlet extends BeGenericServlet { throw e; } } - ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all property scopes @GET @Path("/propertyScopes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve all propertyScopes", method = "GET", summary = "Retrieve all propertyScopes", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns propertyScopes Ok"), - @ApiResponse(responseCode = "404", description = "No propertyScopes were found"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @Operation(description = "Retrieve all propertyScopes", method = "GET", summary = "Retrieve all propertyScopes", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns propertyScopes Ok"), + @ApiResponse(responseCode = "404", description = "No propertyScopes were found"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getPropertyScopes(@Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + 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); @@ -469,25 +421,22 @@ public class ElementServlet extends BeGenericServlet { throw e; } } - ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all artifact types @GET @Path("/artifactTypes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve all artifactTypes", method = "GET", summary = "Retrieve all artifactTypes", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns artifactTypes Ok"), - @ApiResponse(responseCode = "404", description = "No artifactTypes were found"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @Operation(description = "Retrieve all artifactTypes", method = "GET", summary = "Retrieve all artifactTypes", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns artifactTypes Ok"), + @ApiResponse(responseCode = "404", description = "No artifactTypes were found"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getArtifactTypes(@Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + 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); @@ -495,12 +444,11 @@ public class ElementServlet extends BeGenericServlet { log.debug("No artifact types were found"); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); } else { - - Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getDefaultMinutes(); + Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout() + .getDefaultMinutes(); ArtifactTypesInfo typesResponse = new ArtifactTypesInfo(); typesResponse.setArtifactTypes(either.left().value()); typesResponse.setHeatDefaultTimeout(defaultHeatTimeout); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse); } } catch (Exception e) { @@ -509,30 +457,29 @@ public class ElementServlet extends BeGenericServlet { throw e; } } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all followed resources and services @GET @Path("/followed") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Retrieve all followed", method = "GET", summary = "Retrieve all followed", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns followed Ok"), - @ApiResponse(responseCode = "404", description = "No followed were found"), - @ApiResponse(responseCode = "404", description = "User not found"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns followed Ok"), + @ApiResponse(responseCode = "404", description = "No followed were found"), + @ApiResponse(responseCode = "404", description = "User not found"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getFollowedResourcesServices(@Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { - + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { try { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); User userData = userAdminManager.getUser(userId, false); - Either>, ResponseFormat> followedResourcesServices = getElementBL(request.getSession().getServletContext()).getFollowed(userData); + 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()); @@ -545,38 +492,33 @@ public class ElementServlet extends BeGenericServlet { throw e; } } - ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all certified resources and services and their last version @GET @Path("/screen") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve catalog resources and services", method = "GET", - summary = "Retrieve catalog resources and services", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns resources and services Ok"), - @ApiResponse(responseCode = "404", description = "No resources and services were found"), - @ApiResponse(responseCode = "404", description = "User not found"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @Operation(description = "Retrieve catalog resources and services", method = "GET", summary = "Retrieve catalog resources and services", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns resources and services Ok"), + @ApiResponse(responseCode = "404", description = "No resources and services were found"), + @ApiResponse(responseCode = "404", description = "User not found"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getCatalogComponents(@Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @QueryParam("excludeTypes") List excludeTypes) throws IOException { - + public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @QueryParam("excludeTypes") List excludeTypes) throws IOException { try { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - - Either>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId, excludeTypes); - + 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()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components"); log.debug("Getting catalog components failed with exception", e); @@ -590,31 +532,27 @@ public class ElementServlet extends BeGenericServlet { public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) { 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); - 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 { - Map, ResponseFormat>> cleanComponentsResult = componentsCleanBusinessLogic.cleanComponents(componentsList); + Map, ResponseFormat>> cleanComponentsResult = componentsCleanBusinessLogic + .cleanComponents(componentsList); Either, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType); - if (cleanResult.isRight()) { log.debug("failed to delete marked components of type {}", nodeType); return buildErrorResponse(cleanResult.right().value()); } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value()); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components"); log.debug("delete marked components failed with exception", e); @@ -626,57 +564,46 @@ public class ElementServlet extends BeGenericServlet { @Path("/ecompPortalMenu") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve ecomp portal menu - MOC", method = "GET", summary = "Retrieve ecomp portal menu", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Retrieve ecomp portal menu")}) + @Operation(description = "Retrieve ecomp portal menu - MOC", method = "GET", summary = "Retrieve ecomp portal menu", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Retrieve ecomp portal menu")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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}]}]}]"); + "[{\"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}]}]}]"); } @GET @Path("/catalogUpdateTime") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve previus and current catalog update time", method = "GET", - summary = "Retrieve previus and current catalog update time", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Retrieve previus and current catalog update time")}) + @Operation(description = "Retrieve previus and current catalog update time", method = "GET", summary = "Retrieve previus and current catalog update time", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Retrieve previus and current catalog update time")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getCatalogUpdateTime(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(post) Start handle request of {}", url); CatalogUpdateTimestamp catalogUpdateTimestamp = getElementBL(request.getSession().getServletContext()).getCatalogUpdateTime(userId); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - catalogUpdateTimestamp); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), catalogUpdateTimestamp); } - // retrieve all artifact types, ui configuration and sdc version @GET @Path("/setup/ui") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve all artifactTypes, ui configuration and sdc version", method = "GET", - summary = "Retrieve all artifactTypes, ui configuration and sdc version", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", - description = "Returns artifactTypes, ui configuration and sdc version Ok"), - @ApiResponse(responseCode = "404", - description = "No artifactTypes were found/no ui configuration were found/no sdc version were found"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @Operation(description = "Retrieve all artifactTypes, ui configuration and sdc version", method = "GET", summary = "Retrieve all artifactTypes, ui configuration and sdc version", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns artifactTypes, ui configuration and sdc version Ok"), + @ApiResponse(responseCode = "404", description = "No artifactTypes were found/no ui configuration were found/no sdc version were found"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getConfCategoriesAndVersion(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response getConfCategoriesAndVersion(@Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(getConsolidated) Start handle request of {}", url); - Map consolidatedObject = new HashMap<>(); - try { ServletContext servletContext = request.getSession().getServletContext(); Map configuration = getConfigurationUi(elementBusinessLogic); @@ -685,22 +612,18 @@ public class ElementServlet extends BeGenericServlet { } else { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); } - Either either = elementBusinessLogic.getAllCategories(userId); if (either.isRight()) { log.debug("No categories were found"); return buildErrorResponse(either.right().value()); } consolidatedObject.put("categories", either.left().value()); - consolidatedObject.put("version", getVersion(servletContext)); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion"); log.debug("method getConfCategoriesAndVersion failed with unexpected exception", e); throw e; } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), consolidatedObject); } @@ -713,9 +636,7 @@ public class ElementServlet extends BeGenericServlet { private Map getConfigurationUi(final ElementBusinessLogic elementBL) { Either defaultHeatTimeout = elementBL.getDefaultHeatTimeout(); Either, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap(); - Map configuration = new HashMap<>(); - if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) { log.debug("heat default timeout was not found"); return configuration; @@ -731,8 +652,6 @@ public class ElementServlet extends BeGenericServlet { configuration.put("resourceTypes", resourceTypesMap.left().value()); configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()); configuration.put("gab", ConfigurationManager.getConfigurationManager().getConfiguration().getGabConfig()); - return configuration; } } - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ExceptionHandlerEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ExceptionHandlerEndpoint.java index 7603d499c5..ff31aa597d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ExceptionHandlerEndpoint.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ExceptionHandlerEndpoint.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.google.gson.Gson; @@ -31,17 +30,16 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.exception.ResponseFormat; -import org.springframework.stereotype.Controller; - import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Controller; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @@ -50,6 +48,7 @@ import javax.ws.rs.core.Response; @Produces(MediaType.APPLICATION_JSON) @Controller public class ExceptionHandlerEndpoint { + private static final Logger log = Logger.getLogger(ExceptionHandlerEndpoint.class); private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); private final ComponentsUtils componentsUtils; @@ -61,14 +60,10 @@ public class ExceptionHandlerEndpoint { @GET @Path("/handleException") @Operation(description = "Handle exception", method = "GET", responses = { - @ApiResponse(responseCode = "500", description = "Internal Error", - content = @Content(schema = @Schema(implementation = Response.class)))}) + @ApiResponse(responseCode = "500", description = "Internal Error", content = @Content(schema = @Schema(implementation = Response.class)))}) public Response sendError() { log.debug("Request is received"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Response.status(responseFormat.getStatus()) - .entity(gson.toJson(responseFormat.getRequestError())) - .build(); + return Response.status(responseFormat.getStatus()).entity(gson.toJson(responseFormat.getRequestError())).build(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GenericArtifactBrowserServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GenericArtifactBrowserServlet.java index be106a1ff7..df83035eef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GenericArtifactBrowserServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GenericArtifactBrowserServlet.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,6 +30,19 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.IOException; +import java.util.Set; +import java.util.stream.Collectors; +import javax.inject.Inject; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +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 org.apache.commons.lang3.tuple.ImmutablePair; import org.onap.sdc.gab.model.GABQuery; import org.onap.sdc.gab.model.GABQuery.GABQueryType; @@ -43,20 +55,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.owasp.esapi.ESAPI; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -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.IOException; -import java.util.Set; -import java.util.stream.Collectors; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog/gab") @Consumes(MediaType.APPLICATION_JSON) @@ -71,10 +69,8 @@ public class GenericArtifactBrowserServlet extends BeGenericServlet { private final ArtifactsBusinessLogic artifactsBusinessLogic; @Inject - public GenericArtifactBrowserServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - ArtifactsBusinessLogic artifactsBusinessLogic, - GenericArtifactBrowserBusinessLogic gabLogic) { + public GenericArtifactBrowserServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + ArtifactsBusinessLogic artifactsBusinessLogic, GenericArtifactBrowserBusinessLogic gabLogic) { super(userBusinessLogic, componentsUtils); this.artifactsBusinessLogic = artifactsBusinessLogic; this.gabLogic = gabLogic; @@ -82,14 +78,12 @@ public class GenericArtifactBrowserServlet extends BeGenericServlet { @POST @Path("/searchFor") - @Operation(description = "Search json paths inside the yaml", method = "POST", - summary = "Returns found entries of json paths", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Returned yaml entries"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) - public Response searchFor( - @Parameter(description = "Generic Artifact search model", required = true) GenericArtifactQueryInfo query, - @Context final HttpServletRequest request) { + @Operation(description = "Search json paths inside the yaml", method = "POST", summary = "Returns found entries of json paths", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Returned yaml entries"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + public Response searchFor(@Parameter(description = "Generic Artifact search model", required = true) GenericArtifactQueryInfo query, + @Context final HttpServletRequest request) { try { ServletContext context = request.getSession().getServletContext(); ImmutablePair immutablePairResponseFormatEither = getArtifactBL(context) @@ -102,11 +96,9 @@ public class GenericArtifactBrowserServlet extends BeGenericServlet { } } - private GABQuery prepareGabQuery(GenericArtifactQueryInfo query, - ImmutablePair immutablePairResponseFormatEither) { + private GABQuery prepareGabQuery(GenericArtifactQueryInfo query, ImmutablePair immutablePairResponseFormatEither) { byte[] content = immutablePairResponseFormatEither.getRight(); Set queryFields = query.getFields().stream().map(ESAPI.encoder()::canonicalize).collect(Collectors.toSet()); return new GABQuery(queryFields, new String(content), GABQueryType.CONTENT); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupEndpoint.java index a820125d18..7b2b22e793 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupEndpoint.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupEndpoint.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -66,70 +65,65 @@ import org.springframework.stereotype.Controller; @Controller @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -public class GroupEndpoint extends BeGenericServlet{ +public class GroupEndpoint extends BeGenericServlet { - private final GroupBusinessLogicNew groupBusinessLogic; private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(GroupEndpoint.class.getName()); + private final GroupBusinessLogicNew groupBusinessLogic; @Inject - public GroupEndpoint(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, GroupBusinessLogicNew groupBusinessLogic) { + public GroupEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, GroupBusinessLogicNew groupBusinessLogic) { super(userBusinessLogic, componentsUtils); this.groupBusinessLogic = groupBusinessLogic; } @POST @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/members") - @Operation(description = "Update group members ", method = "POST", - summary = "Updates list of members and returns it", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "Group members updated"), - @ApiResponse(responseCode = "400", - description = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @Operation(description = "Update group members ", method = "POST", summary = "Updates list of members and returns it", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "Group members updated"), + @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public List updateGroupMembers(@PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @Parameter(description = "List of members unique ids", required = true) List members, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_GROUP_MEMBERS, StatusCode.STARTED," Starting to update Group Members for component {} " , componentId ); + @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, + @Parameter(description = "List of members unique ids", required = true) List members, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_GROUP_MEMBERS, StatusCode.STARTED, " Starting to update Group Members for component {} ", + componentId); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_GROUP_MEMBERS, StatusCode.COMPLETE," Ended update Group Members for component {} " , componentId ); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_GROUP_MEMBERS, StatusCode.COMPLETE, " Ended update Group Members for component {} ", componentId); return groupBusinessLogic.updateMembers(componentId, componentTypeEnum, userId, groupUniqueId, members); } @GET @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties") - @Operation(description = "Get List of properties on a group", method = "GET", - summary = "Returns list of properties", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))), - @ApiResponse(responseCode = "200", description = "Group Updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Get List of properties on a group", method = "GET", summary = "Returns list of properties", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))), + @ApiResponse(responseCode = "200", description = "Group Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public List getGroupProperties( - @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public List getGroupProperties(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("groupUniqueId") final String groupUniqueId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return groupBusinessLogic.getProperties(containerComponentType, userId, componentId, groupUniqueId); } @PUT @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties") - @Operation(description = "Updates List of properties on a group (only values)", method = "PUT", - summary = "Returns updated list of properties", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))), - @ApiResponse(responseCode = "200", description = "Group Updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Updates List of properties on a group (only values)", method = "PUT", summary = "Returns updated list of properties", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))), + @ApiResponse(responseCode = "200", description = "Group Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public List updateGroupProperties( - @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @Parameter(description = "Group Properties to be Updated", required = true) List properties, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public List updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("groupUniqueId") final String groupUniqueId, + @Parameter(description = "Group Properties to be Updated", required = true) List properties, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); return groupBusinessLogic.updateProperties(componentId, componentTypeEnum, userId, groupUniqueId, properties); } 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 d1998d841b..0dcbf8cc14 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -79,117 +78,96 @@ import org.springframework.stereotype.Controller; @Controller public class GroupServlet extends AbstractValidationsServlet { - private static final Logger log = Logger.getLogger(GroupServlet.class); public static final String START_HANDLE_REQUEST = "Start handle request of {}"; + private static final Logger log = Logger.getLogger(GroupServlet.class); private final GroupBusinessLogic groupBL; @Inject - public GroupServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL, - ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, - ServletUtils servletUtils, ResourceImportManager resourceImportManager) { + public GroupServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.groupBL = groupBL; } @POST @Path("/{containerComponentType}/{componentId}/groups/{groupType}") - @Operation(description = "Create group ", method = "POST", - summary = "Creates new group in component and returns it", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Group created"), @ApiResponse(responseCode = "400", - description = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @Operation(description = "Create group ", method = "POST", summary = "Creates new group in component and returns it", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Group created"), + @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { + @PathParam("componentId") final String componentId, @PathParam("groupType") final String type, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(post) Start handle request of {}", url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - GroupDefinition groupDefinition = groupBL - .createGroup(componentId, componentTypeEnum, type, userId); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), - groupDefinition); + GroupDefinition groupDefinition = groupBL.createGroup(componentId, componentTypeEnum, type, userId); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), groupDefinition); } @GET @Path("/{containerComponentType}/{componentId}/groups/{groupId}") - @Operation(description = "Get group artifacts ", method = "GET", - summary = "Returns artifacts metadata according to groupId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "group found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Group not found")}) + @Operation(description = "Get group artifacts ", method = "GET", summary = "Returns artifacts metadata according to groupId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "group found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Group not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { + @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of {}", url); - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either actionResponse = - groupBL.getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false); - + Either actionResponse = groupBL + .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()); - + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); log.debug("getGroupArtifactById unexpected exception", e); throw e; } - } @DELETE @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}") @Operation(description = "Delete Group", method = "DELETE", summary = "Returns deleted group id", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"), - @ApiResponse(responseCode = "400", - description = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"), + @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { + @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST, url); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - GroupDefinition groupDefinition = groupBL - .deleteGroup(componentId, componentTypeEnum, groupId, userId); - + GroupDefinition groupDefinition = groupBL.deleteGroup(componentId, componentTypeEnum, groupId, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), groupDefinition.getUniqueId()); } @PUT @Path("/{containerComponentType}/{componentId}/groups/{groupId}") @Operation(description = "Update Group metadata", method = "PUT", summary = "Returns updated Group", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Group updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "component / group Not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Group updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "component / group Not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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, - @Parameter(description = "GroupDefinition", required = true) GroupDefinition groupData, - @Context final HttpServletRequest request) { + @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "GroupDefinition", required = true) GroupDefinition groupData, + @Context final HttpServletRequest request) { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); GroupDefinition updatedGroup = groupBL.updateGroup(componentId, componentTypeEnum, groupId, userId, groupData); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup); @@ -199,25 +177,21 @@ public class GroupServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Group Metadata", method = "PUT", summary = "Returns updated group definition", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))), - @ApiResponse(responseCode = "200", description = "Group Updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Group Metadata", method = "PUT", summary = "Returns updated group definition", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))), + @ApiResponse(responseCode = "200", description = "Group Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateGroupMetadata(@PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @Parameter(description = "Service object to be Updated", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { - + @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, + @Parameter(description = "Service object to be Updated", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { 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); - try { Either convertResponse = parseToObject(data, () -> GroupDefinition.class); if (convertResponse.isRight()) { @@ -225,26 +199,21 @@ public class GroupServlet extends AbstractValidationsServlet { return buildErrorResponse(convertResponse.right().value()); } GroupDefinition updatedGroup = convertResponse.left().value(); - // Update GroupDefinition ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); Either actionResponse = groupBL - .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true); - + .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true, true); if (actionResponse.isRight()) { log.debug("failed to update GroupDefinition"); return buildErrorResponse(actionResponse.right().value()); } - 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); throw e; } } - } 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 index 69c51a62df..afce970cb7 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,6 +30,14 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.List; +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 org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; @@ -42,15 +49,6 @@ 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") @Tags({@Tag(name = "SDC Internal APIs")}) @@ -58,12 +56,11 @@ import java.util.List; @Controller @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -public class GroupTypesEndpoint extends BeGenericServlet{ +public class GroupTypesEndpoint extends BeGenericServlet { private final GroupTypeBusinessLogic groupTypeBusinessLogic; - public GroupTypesEndpoint(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, GroupTypeBusinessLogic groupTypeBusinessLogic) { + public GroupTypesEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, GroupTypeBusinessLogic groupTypeBusinessLogic) { super(userBusinessLogic, componentsUtils); this.groupTypeBusinessLogic = groupTypeBusinessLogic; } @@ -71,18 +68,14 @@ public class GroupTypesEndpoint extends BeGenericServlet{ @GET @Path("/groupTypes") @Operation(description = "Get group types ", method = "GET", summary = "Returns group types", responses = { - @ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = GroupTypeDefinition.class)))), - @ApiResponse(responseCode = "200", description = "group types found"), @ApiResponse(responseCode = "400", - description = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "500", description = "Internal Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupTypeDefinition.class)))), + @ApiResponse(responseCode = "200", description = "group types found"), + @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "500", description = "Internal Error")}) @ResponseView(mixin = {GroupTypeMixin.class}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public List getGroupTypes(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter( - description = "An optional parameter to indicate the type of the container from where this call is executed") @QueryParam("internalComponentType") String internalComponentType) { + @Parameter(description = "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 0d073b559a..96a8a70954 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.core.JsonProcessingException; @@ -32,6 +31,23 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.tags.Tag; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import javax.inject.Inject; +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 org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic; @@ -65,24 +81,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Tag(name = "SDC Internal APIs") @Server(url = "/sdc2/rest") @@ -96,17 +94,13 @@ public class InputsServlet extends AbstractValidationsServlet { private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(InputsServlet.class.getName()); private static final String START_HANDLE_REQUEST_OF = "(get) Start handle request of {}"; private static final String CREATE_INPUT = "CreateInput"; - private final DataTypeBusinessLogic businessLogic; private final InputsBusinessLogic inputsBusinessLogic; @Inject - public InputsServlet(UserBusinessLogic userBusinessLogic, - InputsBusinessLogic inputsBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - DataTypeBusinessLogic dataTypeBusinessLogic) { + public InputsServlet(UserBusinessLogic userBusinessLogic, InputsBusinessLogic inputsBusinessLogic, + ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, ServletUtils servletUtils, + ResourceImportManager resourceImportManager, DataTypeBusinessLogic dataTypeBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.inputsBusinessLogic = inputsBusinessLogic; this.businessLogic = dataTypeBusinessLogic; @@ -114,59 +108,46 @@ public class InputsServlet extends AbstractValidationsServlet { @POST @Path("/{containerComponentType}/{componentId}/update/inputs") - @Operation(description = "Update resource inputs", method = "POST", summary = "Returns updated input", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Input updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) - public Response updateComponentInputs(@Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME , - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, - @Parameter(description = "json describe the input", required = true) String data, - @Context final HttpServletRequest request) throws JsonProcessingException { - + @Operation(description = "Update resource inputs", method = "POST", summary = "Returns updated input", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Input updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + public Response updateComponentInputs( + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @Parameter(description = "json describe the input", required = true) String data, + @Context final HttpServletRequest request) throws JsonProcessingException { 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()){ + .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); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType); - if (businessLogic == null) { log.debug("Unsupported component type {}", containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR)); } - - Either, ResponseFormat> actionResponse = inputsBusinessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false); - + Either, ResponseFormat> actionResponse = inputsBusinessLogic + .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) { + } catch (Exception e) { log.error("create and associate RI failed with exception: {}", e.getMessage(), e); throw e; } @@ -175,27 +156,25 @@ public class InputsServlet extends AbstractValidationsServlet { @GET @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs") @Operation(description = "Get Inputs only", method = "GET", summary = "Returns Inputs list", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "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) throws IOException { - + @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) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { - Either, ResponseFormat> inputsResponse = inputsBusinessLogic.getComponentInstanceInputs(userId, componentId, instanceId); + Either, ResponseFormat> inputsResponse = inputsBusinessLogic + .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); @@ -206,30 +185,28 @@ public class InputsServlet extends AbstractValidationsServlet { @GET @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties") @Operation(description = "Get properties", method = "GET", summary = "Returns properties list", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "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) throws IOException { - + @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) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { Either, ResponseFormat> inputPropertiesRes = inputsBusinessLogic - .getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId); + .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); + BeEcompErrorManager.getInstance() + .logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId); log.debug("getInputPropertiesForComponentInstance failed with exception", e); throw e; } @@ -238,29 +215,27 @@ public class InputsServlet extends AbstractValidationsServlet { @GET @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs") @Operation(description = "Get inputs", method = "GET", summary = "Returns inputs list", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "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) throws IOException { - + @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); try { - Either, ResponseFormat> inputsRes = - inputsBusinessLogic.getInputsForComponentInput(userId, componentId, inputId); - + Either, ResponseFormat> inputsRes = inputsBusinessLogic + .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); + BeEcompErrorManager.getInstance() + .logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); log.debug("getInputsForComponentInput failed with exception", e); throw e; } @@ -269,98 +244,82 @@ public class InputsServlet extends AbstractValidationsServlet { @GET @Path("/{componentType}/{componentId}/inputs/{inputId}") @Operation(description = "Get inputs", method = "GET", summary = "Returns inputs list", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "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) throws IOException { - + @PathParam("componentId") final String componentId, + @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { - Either inputsRes = - inputsBusinessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false); - + Either inputsRes = inputsBusinessLogic + .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); + BeEcompErrorManager.getInstance() + .logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); log.debug("getInputsForComponentInput failed with exception", e); throw e; } } private Either parseToComponentInstListInput(String json, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(json, user, ComponentInstListInput.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(json, user, ComponentInstListInput.class, AuditingActionEnum.CREATE_RESOURCE, + ComponentTypeEnum.SERVICE); } @POST @Path("/{componentType}/{componentId}/create/inputs") @Operation(description = "Create inputs on service", method = "POST", summary = "Return inputs list", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "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, - @Parameter(description = "ComponentIns Inputs Object to be created", - required = true) String componentInstInputsMapObj) { - - return super.declareProperties(userId, componentId, componentType, componentInstInputsMapObj, - DeclarationTypeEnum.INPUT, request); + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "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, + @Parameter(description = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) { + return super.declareProperties(userId, componentId, componentType, componentInstInputsMapObj, DeclarationTypeEnum.INPUT, request); } @POST @Path("/{componentType}/{componentId}/create/input") @Operation(description = "Create inputs on service", method = "POST", summary = "Return inputs list", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) - public Response createInput(@PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "ComponentIns Inputs Object to be created", - required = true) String componentInstInputsMapObj) { - + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) + public Response createInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) { return createInput(componentId, componentInstInputsMapObj, request, userId); } /** - * Creates a "list input" and updates given list of properties to get value from the input. - * also a data type which has same properties is created. + * Creates a "list input" and updates given list of properties to get value from the input. also a data type which has same properties is created. * the data type will be the entry_schema of the list input. - * @param componentType the container type (service, resource, ...) - * @param componentId the container ID - * @param request HttpServletRequest object - * @param userId the User ID - * @param componentInstInputsMapObj the list of properties to be declared and the "list input" to be created. - * the type of the input must be "list". - * schema.type of the input will be the name of new data type. + * + * @param componentType the container type (service, resource, ...) + * @param componentId the container ID + * @param request HttpServletRequest object + * @param userId the User ID + * @param componentInstInputsMapObj the list of properties to be declared and the "list input" to be created. the type of the input must be + * "list". schema.type of the input will be the name of new data type. * @return the created input */ @POST @Path("/{componentType}/{componentId}/create/listInput") @Operation(description = "Create a list input on service", method = "POST", summary = "Return input", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) - public Response createListInput(@PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "ComponentIns Inputs Object to be created", - required = true) String componentInstInputsMapObj) { - + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) + public Response createListInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("#createListInput: Start handle request of {}", url); try { @@ -368,62 +327,53 @@ public class InputsServlet extends AbstractValidationsServlet { User modifier = new User(); modifier.setUserId(userId); log.debug("modifier id is {}", userId); - - Either componentInstInputsMapRes = - parseToComponentInstListInput(componentInstInputsMapObj, modifier); + Either componentInstInputsMapRes = parseToComponentInstListInput(componentInstInputsMapObj, + modifier); if (componentInstInputsMapRes.isRight()) { log.debug("failed to parse componentInstInputsMap"); return buildErrorResponse(componentInstInputsMapRes.right().value()); } - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); ComponentInstListInput componentInstInputsMap = componentInstInputsMapRes.left().value(); if (log.isDebugEnabled()) { // for inspection on debug - log.debug("parsed componentInstInputsMap={}", - ReflectionToStringBuilder.toString(componentInstInputsMap)); + log.debug("parsed componentInstInputsMap={}", ReflectionToStringBuilder.toString(componentInstInputsMap)); } - Either, ResponseFormat> inputPropertiesRes = inputsBusinessLogic - .createListInput(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); + .createListInput(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); if (inputPropertiesRes.isRight()) { log.debug("failed to create list input 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 list input for service with id: " + componentId); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create list input for service with id: " + componentId); log.debug("createListInput failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - @DELETE @Path("/{componentType}/{componentId}/delete/{inputId}/input") - @Operation(description = "Delete input from service", method = "DELETE", summary = "Delete service input", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Input deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "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, - @Parameter(description = "Service Input to be deleted", required = true) String componentInstInputsMapObj) { - + @Operation(description = "Delete input from service", method = "DELETE", summary = "Delete service input", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Input deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "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, + @Parameter(description = "Service Input to be deleted", required = true) String componentInstInputsMapObj) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - loggerSupportability.log(LoggerSupportabilityActions.DELETE_INPUTS, StatusCode.STARTED,"Starting to delete Inputs for component {} ",componentId + " by " + userId ); - + loggerSupportability.log(LoggerSupportabilityActions.DELETE_INPUTS, StatusCode.STARTED, "Starting to delete Inputs for component {} ", + componentId + " by " + userId); try { InputDefinition deleteInput = inputsBusinessLogic.deleteInput(componentId, userId, inputId); - loggerSupportability.log(LoggerSupportabilityActions.DELETE_INPUTS, StatusCode.COMPLETE,"Ended delete Inputs for component {} ",componentId + " by " + userId ); + loggerSupportability.log(LoggerSupportabilityActions.DELETE_INPUTS, StatusCode.COMPLETE, "Ended delete Inputs for component {} ", + componentId + " by " + userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput); - } catch (ComponentException e){ + } catch (ComponentException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); log.debug("Delete input failed with exception", e); throw e; @@ -432,31 +382,25 @@ public class InputsServlet extends AbstractValidationsServlet { /** * Gets a specific data type associated with a component. + * * @param componentType the container type (service, resource, ...) - * @param componentId the container ID - * @param dataTypeName the data type name - * @param request HttpServletRequest object + * @param componentId the container ID + * @param dataTypeName the data type name + * @param request HttpServletRequest object * @return the data type info */ @GET @Path("/{componentType}/{componentId}/dataType/{dataTypeName}") - @Operation(description = "Get data type in service", method = "GET", summary = "Get data type in service", - responses = {@ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = DataTypeDefinition.class)))), - @ApiResponse(responseCode = "200", description = "Data type found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Data type not found")}) + @Operation(description = "Get data type in service", method = "GET", summary = "Get data type in service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = DataTypeDefinition.class)))), + @ApiResponse(responseCode = "200", description = "Data type found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Data type not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getDataType( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("dataTypeName") final String dataTypeName, - @Context final HttpServletRequest request - ) { + public Response getDataType(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, + @PathParam("dataTypeName") final String dataTypeName, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(getDataType) Start handle request of {}", url); Response response; - try { Either getResult = businessLogic.getPrivateDataType(componentId, dataTypeName); if (getResult.isRight()) { @@ -466,7 +410,8 @@ public class InputsServlet extends AbstractValidationsServlet { Object json = RepresentationUtils.toRepresentation(getResult.left().value()); return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json); } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get data type from service + " + componentId + " + with name: " + dataTypeName); + BeEcompErrorManager.getInstance() + .logBeRestApiGeneralError("Get data type from service + " + componentId + " + with name: " + dataTypeName); log.debug("Get data type failed with exception", e); response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return response; @@ -475,30 +420,25 @@ public class InputsServlet extends AbstractValidationsServlet { /** * Gets a list of data types which a component has. + * * @param componentType the container type (service, resource, ...) - * @param componentId the container ID - * @param request HttpServletRequest object + * @param componentId the container ID + * @param request HttpServletRequest object * @return the list of data types in the component */ @GET @Path("/{componentType}/{componentId}/dataTypes") - @Operation(description = "Get data types that service has", method = "GET", summary = "Get data types in service", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Data type found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @Operation(description = "Get data types that service has", method = "GET", summary = "Get data types in service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Data type found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getDataTypes( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @Context final HttpServletRequest request - ) { + public Response getDataTypes(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, + @Context final HttpServletRequest request) { ComponentsUtils componentsUtils = getComponentsUtils(); String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(getDataType) Start handle request of {}", url); Response response; - try { Either, StorageOperationStatus> getResult = businessLogic.getPrivateDataTypes(componentId); if (getResult.isRight()) { @@ -517,32 +457,27 @@ public class InputsServlet extends AbstractValidationsServlet { /** * Deletes a data type from a component. + * * @param componentType the container type (service, resource, ...) - * @param componentId the container ID - * @param dataTypeName the data type name to be deleted - * @param request HttpServletRequest object + * @param componentId the container ID + * @param dataTypeName the data type name to be deleted + * @param request HttpServletRequest object * @return operation result */ @DELETE @Path("/{componentType}/{componentId}/dataType/{dataTypeName}") - @Operation(description = "Delete data type from service", method = "DELETE", summary = "Delete service input", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Data type deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Data type not found")}) + @Operation(description = "Delete data type from service", method = "DELETE", summary = "Delete service input", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Data type deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Data type not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteDataType( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("dataTypeName") final String dataTypeName, - @Context final HttpServletRequest request - ) { + public Response deleteDataType(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, + @PathParam("dataTypeName") final String dataTypeName, @Context final HttpServletRequest request) { ComponentsUtils componentsUtils = getComponentsUtils(); String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); Response response; - try { Either deleteResult = businessLogic.deletePrivateDataType(componentId, dataTypeName); if (deleteResult.isRight()) { @@ -552,53 +487,45 @@ public class InputsServlet extends AbstractValidationsServlet { Object json = RepresentationUtils.toRepresentation(deleteResult.left().value()); return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json); } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete data type for service + " + componentId + " + with name: " + dataTypeName); + BeEcompErrorManager.getInstance() + .logBeRestApiGeneralError("Delete data type for service + " + componentId + " + with name: " + dataTypeName); log.debug("Delete data type failed with exception", e); response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return response; } } - private Response createInput(String componentId, String data, HttpServletRequest request,String userId) { + private Response createInput(String componentId, String data, HttpServletRequest request, String userId) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, StatusCode.STARTED,"CREATE_INPUTS by user {} ", userId); - - try{ - Either, ActionStatus> inputDefinition = - getInputModel(componentId, data); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, StatusCode.STARTED, "CREATE_INPUTS by user {} ", userId); + try { + Either, ActionStatus> inputDefinition = getInputModel(componentId, data); if (inputDefinition.isRight()) { ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(inputDefinition.right().value()); return buildErrorResponse(responseFormat); } - Map inputs = inputDefinition.left().value(); if (inputs == null || inputs.size() != 1) { log.info("Input content is invalid - {}", data); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); return buildErrorResponse(responseFormat); } - Map.Entry entry = inputs.entrySet().iterator().next(); InputDefinition newInputDefinition = entry.getValue(); newInputDefinition.setParentUniqueId(componentId); String inputName = newInputDefinition.getName(); - - Either, ResponseFormat> addInputEither = - inputsBusinessLogic.addInputToComponent(componentId, inputName, newInputDefinition, userId); - - if(addInputEither.isRight()) { + Either, ResponseFormat> addInputEither = inputsBusinessLogic + .addInputToComponent(componentId, inputName, newInputDefinition, userId); + if (addInputEither.isRight()) { return buildErrorResponse(addInputEither.right().value()); } - - loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, StatusCode.COMPLETE,"CREATE_INPUTS by user {} ", userId); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, StatusCode.COMPLETE, "CREATE_INPUTS by user {} ", userId); return buildOkResponse(newInputDefinition); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_INPUT); log.debug("create input failed with exception", e); - ResponseFormat responseFormat = - getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); return buildErrorResponse(responseFormat); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java index 0f7664b4fe..1fd31db6ed 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.servlets; import com.google.common.collect.ImmutableMap; @@ -29,6 +28,25 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import javax.inject.Inject; +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.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; @@ -51,26 +69,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Consumes(MediaType.APPLICATION_JSON) @@ -84,11 +82,9 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic; @Inject - public InterfaceOperationServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) { + public InterfaceOperationServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, + InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic; } @@ -97,50 +93,41 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/interfaceOperations") - @Operation(description = "Create Interface Operations on Resource", method = "POST", - summary = "Create Interface Operations on Resource", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Create Interface Operations on Resource"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found"), - @ApiResponse(responseCode = "409", description = "Interface Operation already exist")}) + @Operation(description = "Create Interface Operations on Resource", method = "POST", summary = "Create Interface Operations on Resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Create Interface Operations on Resource"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found"), + @ApiResponse(responseCode = "409", description = "Interface Operation already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createInterfaceOperationsOnResource( - @Parameter(description = "Interface Operations to create", required = true) String data, - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + public Response createInterfaceOperationsOnResource(@Parameter(description = "Interface Operations to create", required = true) String data, + @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, false); } - private Response createOrUpdate(String data, ComponentTypeEnum componentType, String componentId, - HttpServletRequest request, String userId, boolean isUpdate) { + private Response createOrUpdate(String data, ComponentTypeEnum componentType, String componentId, HttpServletRequest request, String userId, + boolean isUpdate) { String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); log.debug("Start create or update request of {} with modifier id {}", url, userId); - try { String componentIdLower = componentId.toLowerCase(); - List mappedInterfaceData = getMappedInterfaceData(data, modifier, componentType); Either, ResponseFormat> actionResponse; if (isUpdate) { - actionResponse = - interfaceOperationBusinessLogic.updateInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true); + actionResponse = interfaceOperationBusinessLogic.updateInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true); } else { - actionResponse = - interfaceOperationBusinessLogic.createInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true); + actionResponse = interfaceOperationBusinessLogic.createInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true); } - if (actionResponse.isRight()) { log.error("failed to create or update interface operation"); return buildErrorResponse(actionResponse.right().value()); } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - getFormattedResponse(actionResponse.left().value())); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value())); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update"); log.error("create or update interface Operation with an error", e); @@ -148,17 +135,16 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { } } - private List getMappedInterfaceData(String inputJson, User user, - ComponentTypeEnum componentTypeEnum) { - Either uiComponentEither = - getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user, - UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); + private List getMappedInterfaceData(String inputJson, User user, ComponentTypeEnum componentTypeEnum) { + Either uiComponentEither = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, + componentTypeEnum); return new ArrayList<>(uiComponentEither.left().value().getInterfaces().values()); } private Object getFormattedResponse(List interfaceDefinitions) throws IOException { - Map> allInterfaces = - ImmutableMap.of(JsonPresentationFields.INTERFACES.getPresentation(), interfaceDefinitions); + Map> allInterfaces = ImmutableMap + .of(JsonPresentationFields.INTERFACES.getPresentation(), interfaceDefinitions); return RepresentationUtils.toFilteredRepresentation(allInterfaces); } @@ -166,18 +152,17 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/interfaceOperations") - @Operation(description = "Update Interface Operations on Resource", method = "PUT", - summary = "Update Interface Operations on Resource", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Update Interface Operations on Resource"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found")}) + @Operation(description = "Update Interface Operations on Resource", method = "PUT", summary = "Update Interface Operations on Resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Update Interface Operations on Resource"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateInterfaceOperationsOnResource( - @Parameter(description = "Interface Operations to update", required = true) String data, - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + public Response updateInterfaceOperationsOnResource(@Parameter(description = "Interface Operations to update", required = true) String data, + @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, true); } @@ -185,42 +170,35 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}") - @Operation(description = "Delete Interface Operation from Resource", method = "DELETE", - summary = "Delete Interface Operation from Resource", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found")}) + @Operation(description = "Delete Interface Operation from Resource", method = "DELETE", summary = "Delete Interface Operation from Resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteInterfaceOperationsFromResource( - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId, - @Parameter(description = "Operation Id") @PathParam("operationId") String operationId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + public Response deleteInterfaceOperationsFromResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId, + @Parameter(description = "Operation Id") @PathParam("operationId") String operationId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { return delete(interfaceId, operationId, resourceId, request, userId); } - private Response delete(String interfaceId, String operationId, String componentId, HttpServletRequest request, - String userId) { - + private Response delete(String interfaceId, String operationId, String componentId, HttpServletRequest request, String userId) { String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); log.debug("Start delete request of {} with modifier id {}", url, userId); - try { String componentIdLower = componentId.toLowerCase(); - Either, ResponseFormat> actionResponse = interfaceOperationBusinessLogic.deleteInterfaceOperation( - componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true); + Either, ResponseFormat> actionResponse = interfaceOperationBusinessLogic + .deleteInterfaceOperation(componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true); if (actionResponse.isRight()) { log.error("failed to delete interface operation"); return buildErrorResponse(actionResponse.right().value()); } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - getFormattedResponse(actionResponse.left().value())); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value())); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Interface Operation"); log.error("Delete interface operation with an error", e); @@ -232,41 +210,35 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}") - @Operation(description = "Get Interface Operation from Resource", method = "GET", - summary = "GET Interface Operation from Resource", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found")}) + @Operation(description = "Get Interface Operation from Resource", method = "GET", summary = "GET Interface Operation from Resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getInterfaceOperationsFromResource( - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId, - @Parameter(description = "Operation Id") @PathParam("operationId") String operationId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + public Response getInterfaceOperationsFromResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId, + @Parameter(description = "Operation Id") @PathParam("operationId") String operationId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { return get(interfaceId, operationId, resourceId, request, userId); } - private Response get(String interfaceId, String operationId, String componentId, HttpServletRequest request, - String userId) { + private Response get(String interfaceId, String operationId, String componentId, HttpServletRequest request, String userId) { String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); log.debug("Start get request of {} with modifier id {}", url, userId); - try { String componentIdLower = componentId.toLowerCase(); - Either, ResponseFormat> actionResponse = interfaceOperationBusinessLogic.getInterfaceOperation( - componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true); + Either, ResponseFormat> actionResponse = interfaceOperationBusinessLogic + .getInterfaceOperation(componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true); if (actionResponse.isRight()) { log.error("failed to get interface operation"); return buildErrorResponse(actionResponse.right().value()); } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - getFormattedResponse(actionResponse.left().value())); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value())); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component interface operations"); log.error("get component interface operations failed with exception", e); @@ -278,19 +250,18 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/interfaceOperations") - @Operation(description = "Create Interface Operations on Service", method = "POST", - summary = "Create Interface Operations on Service", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Create Interface Operations on Service"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found"), - @ApiResponse(responseCode = "409", description = "Interface Operation already exist")}) + @Operation(description = "Create Interface Operations on Service", method = "POST", summary = "Create Interface Operations on Service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Create Interface Operations on Service"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found"), + @ApiResponse(responseCode = "409", description = "Interface Operation already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createInterfaceOperationsOnService( - @Parameter(description = "Interface Operations to create", required = true) String data, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + public Response createInterfaceOperationsOnService(@Parameter(description = "Interface Operations to create", required = true) String data, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, false); } @@ -298,18 +269,17 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/interfaceOperations") - @Operation(description = "Update Interface Operations on Service", method = "PUT", - summary = "Update Interface Operations on Service", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Update Interface Operations on Service"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @Operation(description = "Update Interface Operations on Service", method = "PUT", summary = "Update Interface Operations on Service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Update Interface Operations on Service"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateInterfaceOperationsOnService( - @Parameter(description = "Interface Operations to update", required = true) String data, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + public Response updateInterfaceOperationsOnService(@Parameter(description = "Interface Operations to update", required = true) String data, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, true); } @@ -317,19 +287,18 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}") - @Operation(description = "Delete Interface Operation from Service", method = "DELETE", - summary = "Delete Interface Operation from Service", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Service"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @Operation(description = "Delete Interface Operation from Service", method = "DELETE", summary = "Delete Interface Operation from Service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Service"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteInterfaceOperationsFromService( - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId, - @Parameter(description = "Operation Id") @PathParam("operationId") String operationId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + public Response deleteInterfaceOperationsFromService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId, + @Parameter(description = "Operation Id") @PathParam("operationId") String operationId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { return delete(interfaceId, operationId, serviceId, request, userId); } @@ -337,20 +306,18 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}") - @Operation(description = "Get Interface Operation from Service", method = "GET", - summary = "GET Interface Operation from Service", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Get Interface Operation from Service"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @Operation(description = "Get Interface Operation from Service", method = "GET", summary = "GET Interface Operation from Service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Get Interface Operation from Service"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getInterfaceOperationsFromService( - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId, - @Parameter(description = "Operation Id") @PathParam("operationId") String operationId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + public Response getInterfaceOperationsFromService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId, + @Parameter(description = "Operation Id") @PathParam("operationId") String operationId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { return get(interfaceId, operationId, serviceId, request, userId); } } - 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 87c890de1b..de66aa68f0 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.databind.ObjectMapper; @@ -82,45 +81,37 @@ public class LifecycleServlet extends BeGenericServlet { private LifecycleBusinessLogic lifecycleBusinessLogic; @Inject - public LifecycleServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, - LifecycleBusinessLogic lifecycleBusinessLogic) { + public LifecycleServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, LifecycleBusinessLogic lifecycleBusinessLogic) { super(userBusinessLogic, componentsUtils); this.lifecycleBusinessLogic = lifecycleBusinessLogic; } - @POST @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Change Resource lifecycle State", method = "POST", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource state changed"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "409", description = "Resource already exist")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource state changed"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "409", description = "Resource already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response changeResourceState( - @Parameter(description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification") - String jsonChangeInfo, - @Parameter(description = "validValues: resources / services / products", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, - ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam( - value = "componentCollection") final String componentCollection, - @Parameter(schema = @Schema(allowableValues = { - "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify"}), - required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, - @Parameter(description = "id of component to be changed") @PathParam( - value = "componentId") final String componentId, - @Context final HttpServletRequest request, - @Parameter(description = "id of user initiating the operation") @HeaderParam( - value = Constants.USER_ID_HEADER) String userId) throws IOException { + @Parameter(description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification") String jsonChangeInfo, + @Parameter(description = "validValues: resources / services / products", schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam(value = "componentCollection") final String componentCollection, + @Parameter(schema = @Schema(allowableValues = { + "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify"}), required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, + @Parameter(description = "id of component to be changed") @PathParam(value = "componentId") final String componentId, + @Context final HttpServletRequest request, + @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url); - loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.STARTED,"Starting to change lifecycle state to " + lifecycleTransition + " by user " + userId); - + loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.STARTED, + "Starting to change lifecycle state to " + lifecycleTransition + " by user " + userId); Response response = null; - // get modifier from graph log.debug("get modifier properties"); Either eitherGetUser = getUser(request, userId); @@ -128,58 +119,54 @@ public class LifecycleServlet extends BeGenericServlet { 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(ValidationUtils.sanitizeInputString(jsonChangeInfo), LifecycleChangeInfoBase.class) - .getUserRemarks()); + changeInfo = new LifecycleChangeInfoWithAction( + mapper.readValue(ValidationUtils.sanitizeInputString(jsonChangeInfo), LifecycleChangeInfoBase.class).getUserRemarks()); } - } - - catch (Exception e) { + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); log.debug("failed to convert from json {}", jsonChangeInfo, e); getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); throw e; } - LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection); if (componentType != null) { - Either actionResponse = lifecycleBusinessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true); - + Either actionResponse = lifecycleBusinessLogic + .changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true); if (actionResponse.isRight()) { log.info("failed to change resource state"); - loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.ERROR,"failed to change resource state " + lifecycleTransition + " with error " + actionResponse.isRight() + " by user " + userId); + loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.ERROR, + "failed to change resource state " + lifecycleTransition + " with error " + actionResponse.isRight() + " by user " + userId); response = buildErrorResponse(actionResponse.right().value()); return response; } - log.debug("change state successful !!!"); UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value()); Object value = null; try { - value = RepresentationUtils.toRepresentation(componentMetatdata); + value = RepresentationUtils.toRepresentation(componentMetatdata); } catch (IOException e) { e.printStackTrace(); } response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value); - loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE,actionResponse.left().value().getComponentMetadataForSupportLog(),StatusCode.COMPLETE," change state to " + lifecycleTransition + " was successful by user" + userId); + loggerSupportability + .log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, actionResponse.left().value().getComponentMetadataForSupportLog(), + StatusCode.COMPLETE, " change state to " + lifecycleTransition + " was successful by user" + userId); 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); + 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); } @@ -196,5 +183,4 @@ public class LifecycleServlet extends BeGenericServlet { } return Either.left(transitionEnum); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java index 8f00d17168..eb75825f42 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -79,16 +78,12 @@ public class OutputsServlet extends AbstractValidationsServlet { private static final Logger log = Logger.getLogger(OutputsServlet.class); private static final String START_HANDLE_REQUEST_OF = "(get) Start handle request of {}"; - private final OutputsBusinessLogic outputsBusinessLogic; @Inject - public OutputsServlet(final UserBusinessLogic userBusinessLogic, - final OutputsBusinessLogic outputsBusinessLogic, - final ComponentInstanceBusinessLogic componentInstanceBL, - final ComponentsUtils componentsUtils, - final ServletUtils servletUtils, - final ResourceImportManager resourceImportManager) { + public OutputsServlet(final UserBusinessLogic userBusinessLogic, final OutputsBusinessLogic outputsBusinessLogic, + final ComponentInstanceBusinessLogic componentInstanceBL, final ComponentsUtils componentsUtils, + final ServletUtils servletUtils, final ResourceImportManager resourceImportManager) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.outputsBusinessLogic = outputsBusinessLogic; } @@ -97,29 +92,24 @@ public class OutputsServlet extends AbstractValidationsServlet { @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/outputs") @Operation(description = "Get Outputs only", method = "GET", summary = "Returns Outputs list", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "404", description = "Component not found")}) public Response getComponentInstanceOutputs(@PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("instanceId") final String instanceId, + @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) final String userId) { - final String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { - final Either, ResponseFormat> outputsResponse = - outputsBusinessLogic.getComponentInstanceOutputs(userId, componentId, instanceId); + final Either, ResponseFormat> outputsResponse = outputsBusinessLogic + .getComponentInstanceOutputs(userId, componentId, instanceId); if (outputsResponse.isRight()) { log.debug("failed to get component instance outputs {}", componentType); return buildErrorResponse(outputsResponse.right().value()); } final Object outputs = RepresentationUtils.toRepresentation(outputsResponse.left().value()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), outputs); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Outputs " + componentType); log.debug("getOutputs failed with exception", e); @@ -131,61 +121,49 @@ public class OutputsServlet extends AbstractValidationsServlet { @Path("/{componentType}/{componentId}/create/outputs") @Operation(description = "Create outputs on service", method = "POST", summary = "Return outputs list", responses = { @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "404", description = "Component not found")}) - public Response createMultipleOutputs(@PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, + public Response createMultipleOutputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, @Parameter(description = "ComponentIns Outputs Object to be created", required = true) final String componentInstOutputsMapObj) { final String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { return declareAttributes(userId, componentId, componentType, componentInstOutputsMapObj, DeclarationTypeEnum.OUTPUT, request); - } catch (final Exception e) { - BeEcompErrorManager.getInstance() - .logBeRestApiGeneralError("Create outputs for service with id: " + componentId); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create outputs for service with id: " + componentId); log.debug("Attributes declaration failed with exception", e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - private Response declareAttributes(final String userId, - final String componentId, - final String componentType, - final String componentInstOutputsMapObj, - final DeclarationTypeEnum typeEnum, - final HttpServletRequest request) { + private Response declareAttributes(final String userId, final String componentId, final String componentType, + final String componentInstOutputsMapObj, final DeclarationTypeEnum typeEnum, + final HttpServletRequest request) { final ServletContext context = request.getSession().getServletContext(); final String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { final BaseBusinessLogic businessLogic = getBlForDeclaration(typeEnum, context); - // get modifier id final User modifier = new User(userId); log.debug("modifier id is {}", userId); final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - final Either componentInstOutputsMapRes = parseToComponentInstanceMap( - componentInstOutputsMapObj, modifier, componentTypeEnum, ComponentInstOutputsMap.class); + final Either componentInstOutputsMapRes = parseToComponentInstanceMap(componentInstOutputsMapObj, + modifier, componentTypeEnum, ComponentInstOutputsMap.class); if (componentInstOutputsMapRes.isRight()) { log.debug("failed to parse componentInstOutMap"); return buildErrorResponse(componentInstOutputsMapRes.right().value()); } - - final Either, ResponseFormat> attributesAfterDeclaration = - businessLogic.declareAttributes(userId, componentId, componentTypeEnum, componentInstOutputsMapRes.left().value()); + final Either, ResponseFormat> attributesAfterDeclaration = businessLogic + .declareAttributes(userId, componentId, componentTypeEnum, componentInstOutputsMapRes.left().value()); if (attributesAfterDeclaration.isRight()) { log.debug("failed to create outputs for service: {}", componentId); return buildErrorResponse(attributesAfterDeclaration.right().value()); } final Object attributes = RepresentationUtils.toRepresentation(attributesAfterDeclaration.left().value()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), attributes); - } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create outputs for service with id: " + componentId); log.debug("Attributes declaration failed with exception", e); @@ -195,22 +173,16 @@ public class OutputsServlet extends AbstractValidationsServlet { @DELETE @Path("/{componentType}/{componentId}/delete/{outputId}/output") - @Operation(description = "Delete output from service", method = "DELETE", summary = "Delete service output", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Output deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Output not found")}) - public Response deleteOutput(@PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("outputId") final String outputId, - @Context final HttpServletRequest request, + @Operation(description = "Delete output from service", method = "DELETE", summary = "Delete service output", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Output deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Output not found")}) + public Response deleteOutput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, + @PathParam("outputId") final String outputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, @Parameter(description = "Service Output to be deleted", required = true) final String componentInstOutputsMapObj) { - String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { final OutputDefinition deleteOutput = outputsBusinessLogic.deleteOutput(componentId, userId, outputId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteOutput); @@ -220,5 +192,4 @@ public class OutputsServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - } 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 index 141d4cb492..eaa9af4669 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -32,6 +31,24 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.inject.Inject; +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.lang3.StringUtils; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; @@ -59,24 +76,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; /** * Provides REST API to create, retrieve, update, delete a policy */ @@ -90,15 +89,12 @@ import java.util.stream.Collectors; public class PolicyServlet extends AbstractValidationsServlet { private static final Logger log = Logger.getLogger(PolicyServlet.class); - private final PolicyBusinessLogic policyBusinessLogic; private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceServlet.class.getName()); + private final PolicyBusinessLogic policyBusinessLogic; @Inject - public PolicyServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - PolicyBusinessLogic policyBusinessLogic) { + public PolicyServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, + ServletUtils servletUtils, ResourceImportManager resourceImportManager, PolicyBusinessLogic policyBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.policyBusinessLogic = policyBusinessLogic; this.servletUtils = servletUtils; @@ -109,101 +105,100 @@ public class PolicyServlet extends AbstractValidationsServlet { @POST @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}") @Operation(description = "Create Policy", method = "POST", summary = "Returns created Policy", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Policy created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Policy already exist"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Policy created"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Policy already exist"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createPolicy(@PathParam("componentId") final String containerComponentId, @Parameter(description = "valid values: resources / services", - schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Context final HttpServletRequest request) { + public Response createPolicy(@PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { init(); - - loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.STARTED,"Starting to create Policy by user {} containerComponentId={}" , userId , containerComponentId ); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.STARTED, "Starting to create Policy by user {} containerComponentId={}", + userId, containerComponentId); ComponentTypeEnum componentType = validateComponentTypeAndUserId(containerComponentType, userId); PolicyDefinition policy = policyBusinessLogic.createPolicy(componentType, containerComponentId, policyTypeName, userId, true); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.COMPLETE,"Ended create Policy by user {} containerComponentId={}" , userId , containerComponentId); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.COMPLETE, "Ended create Policy by user {} containerComponentId={}", userId, + containerComponentId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), policy); } @PUT @Path("/{containerComponentType}/{componentId}/policies/{policyId}") @Operation(description = "Update Policy metadata", method = "PUT", summary = "Returns updated Policy", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Policy updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "component / policy Not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Policy updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "component / policy Not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updatePolicy(@PathParam("componentId") final String containerComponentId, @Parameter( - description = "valid values: resources / services", - schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Parameter(description = "PolicyDefinition", required = true) String policyData, - @Context final HttpServletRequest request) { + public Response updatePolicy(@PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Parameter(description = "PolicyDefinition", required = true) String policyData, + @Context final HttpServletRequest request) { init(); - - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED,"Starting to update Policy by user {} containerComponentId={}" , userId , containerComponentId); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED, "Starting to update Policy by user {} containerComponentId={}", + userId, containerComponentId); PolicyDefinition policyDefinition = convertJsonToObjectOfClass(policyData, PolicyDefinition.class); policyDefinition.setUniqueId(policyId); - policyDefinition = policyBusinessLogic.updatePolicy(validateComponentTypeAndUserId(containerComponentType, userId), containerComponentId, policyDefinition, userId, true); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE,"Ended update Policy by user {} containerComponentId={}" , userId , containerComponentId); + policyDefinition = policyBusinessLogic + .updatePolicy(validateComponentTypeAndUserId(containerComponentType, userId), containerComponentId, policyDefinition, userId, true); + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE, "Ended update Policy by user {} containerComponentId={}", + userId, containerComponentId); return buildOkResponse(policyDefinition); - } @GET @Path("/{containerComponentType}/{componentId}/policies/{policyId}") @Operation(description = "Get Policy", method = "GET", summary = "Returns Policy", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Policy was found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "component / policy Not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Policy was found"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "component / policy Not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getPolicy(@PathParam("componentId") final String containerComponentId, @Parameter( - description = "valid values: resources / services", - schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Context final HttpServletRequest request) { + public Response getPolicy(@PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { init(); - - PolicyDefinition policy = policyBusinessLogic.getPolicy(validateComponentTypeAndUserId(containerComponentType, - userId), containerComponentId, policyId, userId); + PolicyDefinition policy = policyBusinessLogic + .getPolicy(validateComponentTypeAndUserId(containerComponentType, userId), containerComponentId, policyId, userId); return buildOkResponse(policy); } @DELETE @Path("/{containerComponentType}/{componentId}/policies/{policyId}") @Operation(description = "Delete Policy", method = "DELETE", summary = "No body", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "204", description = "Policy was deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "component / policy Not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "204", description = "Policy was deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "component / policy Not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deletePolicy(@PathParam("componentId") final String containerComponentId, @Parameter( - description = "valid values: resources / services", - schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Context final HttpServletRequest request) { + public Response deletePolicy(@PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { init(); - ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId); PolicyDefinition policyDefinition = policyBusinessLogic.deletePolicy(componentTypeEnum, containerComponentId, policyId, userId, true); return buildOkResponse(policyDefinition); @@ -212,28 +207,28 @@ public class PolicyServlet extends AbstractValidationsServlet { @PUT @Path("/{containerComponentType}/{componentId}/policies/{policyId}/undeclare") @Operation(description = "undeclare Policy", method = "PUT", summary = "No body", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "204", description = "Policy was undeclared"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "component / policy Not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "204", description = "Policy was undeclared"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "component / policy Not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId, @Parameter( - description = "valid values: resources / services", - schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Context final HttpServletRequest request) { + public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { init(); Response response = null; try { ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId); - Either undeclarePolicy = policyBusinessLogic.undeclarePolicy(componentTypeEnum, containerComponentId, policyId, userId, true); - if (undeclarePolicy.isLeft()){ + Either undeclarePolicy = policyBusinessLogic + .undeclarePolicy(componentTypeEnum, containerComponentId, policyId, userId, true); + if (undeclarePolicy.isLeft()) { response = buildOkResponse(undeclarePolicy.left().value()); - } else{ + } else { response = buildErrorResponse(undeclarePolicy.right().value()); } } catch (Exception e) { @@ -245,58 +240,53 @@ public class PolicyServlet extends AbstractValidationsServlet { @GET @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties") - @Operation(description = "Get component policy properties", method = "GET", - summary = "Returns component policy properties", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDataDefinition.class)))), - @ApiResponse(responseCode = "200", description = "Properties found"), @ApiResponse(responseCode = "400", - description = "invalid content - Error: containerComponentType is invalid"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Componentorpolicy not found"), - @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")}) + @Operation(description = "Get component policy properties", method = "GET", summary = "Returns component policy properties", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDataDefinition.class)))), + @ApiResponse(responseCode = "200", description = "Properties found"), + @ApiResponse(responseCode = "400", description = "invalid content - Error: containerComponentType is invalid"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Componentorpolicy not found"), + @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getPolicyProperties(@Parameter( - description = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId, - @Parameter(description = "valid values: resources / services", - schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME , - ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Parameter( - description = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId, - @Parameter(description = "the userid", - required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { + public Response getPolicyProperties( + @Parameter(description = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, + @Parameter(description = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId, + @Parameter(description = "the userid", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { init(); - List propertyDataDefinitionList = policyBusinessLogic.getPolicyProperties( - convertToComponentType(containerComponentType), containerComponentId, policyId, userId); + List propertyDataDefinitionList = policyBusinessLogic + .getPolicyProperties(convertToComponentType(containerComponentType), containerComponentId, policyId, userId); return buildOkResponse(propertyDataDefinitionList); } @PUT @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties") - @Operation(description = "Update Policy properties", method = "PUT", summary = "Returns updated Policy", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Policy properties updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "component / policy Not found")}) + @Operation(description = "Update Policy properties", method = "PUT", summary = "Returns updated Policy", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Policy properties updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "component / policy Not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId, @Parameter( - description = "valid values: resources / services", - schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Parameter(description = "PolicyDefinition", required = true) String policyData, - @Context final HttpServletRequest request) { + public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Parameter(description = "PolicyDefinition", required = true) String policyData, + @Context final HttpServletRequest request) { init(); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED,"Starting to update Policy Properties by user {} containerComponentId={}" , userId , containerComponentId); - + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED, + "Starting to update Policy Properties by user {} containerComponentId={}", userId, containerComponentId); ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId); PropertyDataDefinition[] propertyDataDefinitions = convertJsonToObjectOfClass(policyData, PropertyDataDefinition[].class); - List propertyDataDefinitionList = policyBusinessLogic.updatePolicyProperties(componentTypeEnum, - containerComponentId, policyId, propertyDataDefinitions, userId, true); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED,"Starting to update Policy Properties by user {} containerComponentId={}" , userId , containerComponentId); + List propertyDataDefinitionList = policyBusinessLogic + .updatePolicyProperties(componentTypeEnum, containerComponentId, policyId, propertyDataDefinitions, userId, true); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED, + "Starting to update Policy Properties by user {} containerComponentId={}", userId, containerComponentId); return buildOkResponse(propertyDataDefinitionList); } @@ -313,70 +303,61 @@ public class PolicyServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "update policy targets", method = "POST", summary = "Returns updated Policy", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Policy target updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Policy target updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId, @Parameter( - description = "valid values: resources / services", - schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", - required = true) String userId, - @Context final HttpServletRequest request, List requestJson) { + public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId, + @Parameter(description = "valid values: resources / services", schema = @Schema(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) @Parameter(description = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request, List requestJson) { Map> policyTargetTypeListMap = updatePolicyTargetsFromDTO(requestJson); - PolicyDefinition policyDefinition = updatePolicyTargetsFromMap(policyTargetTypeListMap, containerComponentType, containerComponentId, policyId, userId); + PolicyDefinition policyDefinition = updatePolicyTargetsFromMap(policyTargetTypeListMap, containerComponentType, containerComponentId, + policyId, userId); return buildOkResponse(policyDefinition); - } @POST @Path("/{componentType}/{componentId}/create/policies") - @Operation(description = "Create policies on service", method = "POST", summary = "Return policies list", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Component found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Component not found")}) + @Operation(description = "Create policies on service", method = "POST", summary = "Return policies list", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response declareProperties(@PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "ComponentIns policies Object to be created", - required = true) String componentInstPoliciesMapObj) { - - return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj, - DeclarationTypeEnum.POLICY, request); + public Response declareProperties(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "ComponentIns policies Object to be created", required = true) String componentInstPoliciesMapObj) { + return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj, DeclarationTypeEnum.POLICY, request); } - - private PolicyDefinition updatePolicyTargetsFromMap(Map> policyTarget, String containerComponentType, String containerComponentId, String policyId, String userId) { + private PolicyDefinition updatePolicyTargetsFromMap(Map> policyTarget, String containerComponentType, + String containerComponentId, String policyId, String userId) { ComponentTypeEnum componentTypeEnum = convertToComponentType(containerComponentType); return policyBusinessLogic.updatePolicyTargets(componentTypeEnum, containerComponentId, policyId, policyTarget, userId); } private Map> updatePolicyTargetsFromDTO(List targetDTOList) { - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED,"Starting to update Policy target"); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED, "Starting to update Policy target"); Map> policyTarget = new HashMap<>(); for (PolicyTargetDTO currentTarget : targetDTOList) { - if(!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())){ + if (!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())) { throw new ByActionStatusComponentException(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, currentTarget.getType()); } } - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE,"Ended update Policy target"); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE, "Ended update Policy target"); return policyTarget; } - public boolean addTargetsByType(Map> policyTarget, String type, List uniqueIds) { PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type); - if(targetTypeEnum != null){ + if (targetTypeEnum != null) { policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds)); return true; - } - else{ + } else { return false; } } 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 index 6c7bf2178c..2dcbda499c 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,6 +30,14 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.List; +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 org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; @@ -43,15 +50,6 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; 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") @Tags({@Tag(name = "SDC Internal APIs")}) @@ -59,14 +57,13 @@ import java.util.List; @Controller @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -public class PolicyTypesEndpoint extends BeGenericServlet{ +public class PolicyTypesEndpoint extends BeGenericServlet { private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class); - private final PolicyTypeBusinessLogic policyTypeBusinessLogic; - public PolicyTypesEndpoint(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, PolicyTypeBusinessLogic policyTypeBusinessLogic) { + public PolicyTypesEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, + PolicyTypeBusinessLogic policyTypeBusinessLogic) { super(userBusinessLogic, componentsUtils); this.policyTypeBusinessLogic = policyTypeBusinessLogic; } @@ -74,16 +71,15 @@ public class PolicyTypesEndpoint extends BeGenericServlet{ @GET @Path("/policyTypes") @Operation(description = "Get policy types ", method = "GET", summary = "Returns policy types", responses = { - @ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = PolicyTypeDefinition.class)))), - @ApiResponse(responseCode = "200", description = "policy types found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PolicyTypeDefinition.class)))), + @ApiResponse(responseCode = "200", description = "policy types found"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")}) @ResponseView(mixin = {PolicyTypeMixin.class}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public List getPolicyTypes(@Parameter(description = "An optional parameter to indicate the type of the container from where this call is executed") - @QueryParam("internalComponentType") String internalComponentType, - @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public List getPolicyTypes( + @Parameter(description = "An optional parameter to indicate the type of the container from where this call is executed") @QueryParam("internalComponentType") String internalComponentType, + @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { log.debug("(get) Start handle request of GET policyTypes"); return policyTypeBusinessLogic.getAllPolicyTypes(userId, internalComponentType); } 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 f115f77a86..4a0f6cb580 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.annotation.JsonFilter; @@ -31,6 +30,13 @@ import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; @@ -44,23 +50,20 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - public class RepresentationUtils { private static final Logger log = Logger.getLogger(RepresentationUtils.class); + private static final String EMPTY = "empty"; + private static final String REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER = "removeIsEmptyFromCollections"; + private static final ImmutableMap, Class> IS_EMPTY_FILTER_MIXIN = ImmutableMap., Class>builder() + .put(Collection.class, IsEmptyFilterMixIn.class).put(List.class, IsEmptyFilterMixIn.class).put(Set.class, IsEmptyFilterMixIn.class) + .put(HashMap.class, IsEmptyFilterMixIn.class).put(ArrayList.class, IsEmptyFilterMixIn.class).put(HashSet.class, IsEmptyFilterMixIn.class) + .put(InterfaceDefinition.class, IsEmptyFilterMixIn.class).put(Resource.class, IsEmptyFilterMixIn.class) + .put(ToscaDataDefinition.class, IsEmptyFilterMixIn.class).build(); 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()); @@ -78,23 +81,15 @@ public class RepresentationUtils { 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 * @@ -103,7 +98,6 @@ public class RepresentationUtils { * @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); @@ -121,19 +115,15 @@ public class RepresentationUtils { } 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, boolean validateTimeout) { - JsonObject jsonElement = new JsonObject(); ArtifactDefinition resourceInfo = null; - if (StringUtils.isEmpty(content)) { throw new ByActionStatusComponentException(ActionStatus.MISSING_BODY); } - try { Gson gson = new Gson(); jsonElement = gson.fromJson(content, jsonElement.getClass()); @@ -146,7 +136,6 @@ public class RepresentationUtils { elementsToValidate.put(Constants.ARTIFACT_TIMEOUT, jsonElement.get(Constants.ARTIFACT_TIMEOUT)); } validateMandatoryProperties(elementsToValidate); - if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) { String groupValueUpper = artifactGroupValue.getAsString().toUpperCase(); if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) { @@ -172,20 +161,16 @@ public class RepresentationUtils { 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 (ComponentException ce) { BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), ce); throw ce; - } - catch (Exception e) { + } 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; } @@ -205,26 +190,17 @@ public class RepresentationUtils { mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setMixIns(IS_EMPTY_FILTER_MIXIN); - return mapper.writer(new SimpleFilterProvider().addFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER, - SerializeExceptFilter.serializeAllExcept(EMPTY))).writeValueAsString(elementToRepresent); + return mapper + .writer(new SimpleFilterProvider().addFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER, SerializeExceptFilter.serializeAllExcept(EMPTY))) + .writeValueAsString(elementToRepresent); } - @JsonFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER) - private static class IsEmptyFilterMixIn {} + public static class ResourceRep { - private static final String EMPTY = "empty"; - private static final String REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER = "removeIsEmptyFromCollections"; - private static final ImmutableMap,Class> IS_EMPTY_FILTER_MIXIN = - ImmutableMap.,Class>builder() - .put(Collection.class,IsEmptyFilterMixIn.class) - .put(List.class,IsEmptyFilterMixIn.class) - .put(Set.class,IsEmptyFilterMixIn.class) - .put(HashMap.class,IsEmptyFilterMixIn.class) - .put(ArrayList.class,IsEmptyFilterMixIn.class) - .put(HashSet.class,IsEmptyFilterMixIn.class) - .put(InterfaceDefinition.class,IsEmptyFilterMixIn.class) - .put(Resource.class,IsEmptyFilterMixIn.class) - .put(ToscaDataDefinition.class,IsEmptyFilterMixIn.class) - .build(); + } + @JsonFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER) + private static class IsEmptyFilterMixIn { + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementServlet.java index 2d2b21e4ac..6164cd1f08 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementServlet.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -28,6 +27,22 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.List; +import java.util.Optional; +import javax.inject.Inject; +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.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.RequirementBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; @@ -48,23 +63,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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; -import java.util.Optional; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Consumes(MediaType.APPLICATION_JSON) @@ -73,15 +71,14 @@ import java.util.Optional; @Servers({@Server(url = "/sdc2/rest")}) @Controller public class RequirementServlet extends AbstractValidationsServlet { + private static final Logger LOGGER = Logger.getLogger(RequirementServlet.class); private final RequirementBusinessLogic requirementBusinessLogic; @Inject - public RequirementServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - RequirementBusinessLogic requirementBusinessLogic) { + public RequirementServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, + RequirementBusinessLogic requirementBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.requirementBusinessLogic = requirementBusinessLogic; } @@ -90,61 +87,50 @@ public class RequirementServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/requirements") - @Operation(description = "Create requirements on resource", method = "POST", - summary = "Create requirements on resource", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Create requirements"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "requirement already exist")}) + @Operation(description = "Create requirements on resource", method = "POST", summary = "Create requirements on resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Create requirements"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "requirement already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createRequirementsOnResource( - @Parameter(description = "Requirement to create", required = true) String data, - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, "resources" , resourceId, request, - userId, false, "createRequirements"); + public Response createRequirementsOnResource(@Parameter(description = "Requirement to create", required = true) String data, + @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, "resources", resourceId, request, userId, false, "createRequirements"); } - @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/requirements") - @Operation(description = "Update Requirements on resource", method = "PUT", - summary = "Update Requirements on resource", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Update Requirements"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Requirements on resource", method = "PUT", summary = "Update Requirements on resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Update Requirements"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateRequirementsOnResource( - @Parameter(description = "Requirements to update", required = true) String data, - @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, "resources", resourceId, request, - userId, true, "updateRequirements"); + public Response updateRequirementsOnResource(@Parameter(description = "Requirements to update", required = true) String data, + @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, "resources", resourceId, request, userId, true, "updateRequirements"); } @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/requirements/{requirementId}") - @Operation(description = "Get Requirement from resource", method = "GET", summary = "GET Requirement from resource", - responses = {@ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), - @ApiResponse(responseCode = "201", description = "GET requirement"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Get Requirement from resource", method = "GET", summary = "GET Requirement from resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), + @ApiResponse(responseCode = "201", description = "GET requirement"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getRequirementsFromResource( - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response getRequirementsFromResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return get(requirementId, resourceId, request, userId); } @@ -152,18 +138,16 @@ public class RequirementServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/resources/{resourceId}/requirements/{requirementId}") - @Operation(description = "Delete requirements from resource", method = "DELETE", - summary = "Delete requirements from resource", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Delete requirement"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Delete requirements from resource", method = "DELETE", summary = "Delete requirements from resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Delete requirement"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteRequirementsFromResource( - @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, - @Parameter(description = "requirement Id") @PathParam("requirementId") String requirementId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response deleteRequirementsFromResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId, + @Parameter(description = "requirement Id") @PathParam("requirementId") String requirementId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return delete(requirementId, resourceId, request, userId); } @@ -171,120 +155,97 @@ public class RequirementServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/requirements") - @Operation(description = "Create requirements on service", method = "POST", - summary = "Create requirements on service", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Create Requirements"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Requirement already exist")}) + @Operation(description = "Create requirements on service", method = "POST", summary = "Create requirements on service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Create Requirements"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Requirement already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createRequirementsOnService( - @Parameter(description = "Requirements to create", required = true) String data, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, "services" , serviceId, request, userId, - false , "createRequirements"); + public Response createRequirementsOnService(@Parameter(description = "Requirements to create", required = true) String data, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, "services", serviceId, request, userId, false, "createRequirements"); } - @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/requirements") - @Operation(description = "Update requirements on service", method = "PUT", - summary = "Update requirements on service", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Update requirements"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update requirements on service", method = "PUT", summary = "Update requirements on service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Update requirements"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateRequirementsOnService( - @Parameter(description = "Requirements to update", required = true) String data, - @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, "services", serviceId, request, userId, - true, "updateRequirements"); + public Response updateRequirementsOnService(@Parameter(description = "Requirements to update", required = true) String data, + @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, "services", serviceId, request, userId, true, "updateRequirements"); } @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/requirements/{requirementId}") - @Operation(description = "Get requirement from service", method = "GET", summary = "GET requirement from service", - responses = {@ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), - @ApiResponse(responseCode = "201", description = "GET Requirements"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Get requirement from service", method = "GET", summary = "GET requirement from service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), + @ApiResponse(responseCode = "201", description = "GET Requirements"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getRequirementsOnService( - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response getRequirementsOnService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return get(requirementId, serviceId, request, userId); } - @DELETE @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/services/{serviceId}/requirements/{requirementId}") - @Operation(description = "Delete requirement from service", method = "DELETE", - summary = "Delete requirement from service", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Delete Requirements"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Delete requirement from service", method = "DELETE", summary = "Delete requirement from service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Delete Requirements"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteRequirementsOnService( - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response deleteRequirementsOnService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { return delete(requirementId, serviceId, request, userId); } - - private Response createOrUpdate (String data, String componentType, String componentId, - HttpServletRequest request, String userId, - boolean isUpdate, String errorContext) { + private Response createOrUpdate(String data, String componentType, String componentId, HttpServletRequest request, String userId, + boolean isUpdate, String errorContext) { String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId); - try { String componentIdLower = componentId.toLowerCase(); - - Either, ResponseFormat> mappedRequirementDataEither = - getMappedRequirementData(data, modifier, ComponentTypeEnum.findByParamName(componentType)); - if(mappedRequirementDataEither.isRight()) { + Either, ResponseFormat> mappedRequirementDataEither = getMappedRequirementData(data, modifier, + ComponentTypeEnum.findByParamName(componentType)); + if (mappedRequirementDataEither.isRight()) { LOGGER.error("Failed to create or update requirements"); return buildErrorResponse(mappedRequirementDataEither.right().value()); } List mappedRequirementData = mappedRequirementDataEither.left().value(); Either, ResponseFormat> actionResponse; - if(isUpdate) { - actionResponse = requirementBusinessLogic.updateRequirements(componentIdLower, mappedRequirementData, modifier, - errorContext, true); + if (isUpdate) { + actionResponse = requirementBusinessLogic.updateRequirements(componentIdLower, mappedRequirementData, modifier, errorContext, true); } else { - actionResponse = requirementBusinessLogic.createRequirements(componentIdLower, mappedRequirementData, modifier, - errorContext, true); + actionResponse = requirementBusinessLogic.createRequirements(componentIdLower, mappedRequirementData, modifier, errorContext, true); } - if (actionResponse.isRight()) { LOGGER.error("Failed to create or update requirements"); return buildErrorResponse(actionResponse.right().value()); } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("requirements create or update"); LOGGER.error("Failed to create or update requirements with an error", e); @@ -292,19 +253,15 @@ public class RequirementServlet extends AbstractValidationsServlet { } } - private Response get (String requirementIdToGet, String componentId, - HttpServletRequest request, String userId){ + private Response get(String requirementIdToGet, String componentId, HttpServletRequest request, String userId) { String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); LOGGER.debug("Start get request of {} with modifier id {}", url, userId); - try { String componentIdLower = componentId.toLowerCase(); - Either actionResponse = requirementBusinessLogic - .getRequirement(componentIdLower, requirementIdToGet, modifier, true); + .getRequirement(componentIdLower, requirementIdToGet, modifier, true); if (actionResponse.isRight()) { LOGGER.error("failed to get requirements"); return buildErrorResponse(actionResponse.right().value()); @@ -318,19 +275,15 @@ public class RequirementServlet extends AbstractValidationsServlet { } } - private Response delete (String requirementId, String componentId, HttpServletRequest - request, String userId){ + private Response delete(String requirementId, String componentId, HttpServletRequest request, String userId) { String url = request.getMethod() + " " + request.getRequestURI(); - User modifier = new User(); modifier.setUserId(userId); LOGGER.debug("Start delete request of {} with modifier id {}", url, userId); - try { String componentIdLower = componentId.toLowerCase(); - Either actionResponse = requirementBusinessLogic - .deleteRequirement(componentIdLower, requirementId, modifier, true); + .deleteRequirement(componentIdLower, requirementId, modifier, true); if (actionResponse.isRight()) { LOGGER.error("failed to delete requirements"); return buildErrorResponse(actionResponse.right().value()); @@ -345,14 +298,12 @@ public class RequirementServlet extends AbstractValidationsServlet { } private Either, ResponseFormat> getMappedRequirementData(String inputJson, User user, - ComponentTypeEnum componentTypeEnum){ + ComponentTypeEnum componentTypeEnum) { Either mappedData = getComponentsUtils() - .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, - AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); - Optional> requirementDefinitionList = mappedData.left().value() - .getRequirements().values().stream().findFirst(); - return requirementDefinitionList., ResponseFormat>> - map(Either::left).orElseGet(() -> Either.right(getComponentsUtils() - .getResponseFormat(ActionStatus.GENERAL_ERROR))); + .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, + componentTypeEnum); + Optional> requirementDefinitionList = mappedData.left().value().getRequirements().values().stream().findFirst(); + return requirementDefinitionList., ResponseFormat>>map(Either::left) + .orElseGet(() -> Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); } } 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 3a28206823..ebe3472d8b 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,6 +30,21 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.File; +import java.io.FileNotFoundException; +import javax.inject.Inject; +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 org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; @@ -49,22 +63,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.zip.exception.ZipException; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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 java.io.File; -import java.io.FileNotFoundException; - /** * Root resource (exposed at "/" path) */ @@ -75,22 +73,79 @@ import java.io.FileNotFoundException; @Controller public class ResourceUploadServlet extends AbstractValidationsServlet { - private static final Logger log = Logger.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"; + private static final Logger log = Logger.getLogger(ResourceUploadServlet.class); @Inject - public ResourceUploadServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager) { + public ResourceUploadServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); } + @POST + @Path("/{resourceAuthority}") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @Operation(description = "Create Resource from yaml", method = "POST", summary = "Returns created resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Resource already exist")}) + @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) + public Response uploadMultipart( + @Parameter(description = "validValues: normative-resource / user-resource", schema = @Schema(allowableValues = {NORMATIVE_TYPE_RESOURCE, + USER_TYPE_RESOURCE, USER_TYPE_RESOURCE_UI_IMPORT})) @PathParam(value = "resourceAuthority") final String resourceAuthority, + @Parameter(description = "FileInputStream") @FormDataParam("resourceZip") File file, + @Parameter(description = "ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader, + @Parameter(description = "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) throws FileNotFoundException, ZipException { + 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 != 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); + throw e; + } + } + 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); + // @formatter:off + 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); + // @formatter:on private String urlPath; private boolean isBackEndImport, isUserTypeResource; @@ -124,68 +179,4 @@ public class ResourceUploadServlet extends AbstractValidationsServlet { return isUserTypeResource; } } - - @POST - @Path("/{resourceAuthority}") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Resource from yaml", method = "POST", summary = "Returns created resource", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Resource already exist")}) - @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response uploadMultipart( - @Parameter(description = "validValues: normative-resource / user-resource", - schema = @Schema(allowableValues = {NORMATIVE_TYPE_RESOURCE , - USER_TYPE_RESOURCE,USER_TYPE_RESOURCE_UI_IMPORT})) @PathParam( - value = "resourceAuthority") final String resourceAuthority, - @Parameter(description = "FileInputStream") @FormDataParam("resourceZip") File file, - @Parameter(description = "ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader, - @Parameter(description = "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) throws FileNotFoundException, ZipException { - - 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 != 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); - throw e; - } - } } 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 43fa3786ec..9377820d43 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -104,11 +103,9 @@ public class ResourcesServlet extends AbstractValidationsServlet { private final ResourceBusinessLogic resourceBusinessLogic; @Inject - public ResourcesServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ResourceBusinessLogic resourceBusinessLogic, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager) { + public ResourcesServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ResourceBusinessLogic resourceBusinessLogic, ComponentsUtils componentsUtils, ServletUtils servletUtils, + ResourceImportManager resourceImportManager) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.resourceBusinessLogic = resourceBusinessLogic; } @@ -118,28 +115,26 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Create Resource", method = "POST", summary = "Returns created resource", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "201", description = "Resource created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Resource already exist")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "201", description = "Resource created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Resource already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createResource(@Parameter(description = "Resource object to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException, ZipException { - + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException, ZipException { userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); init(); - 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); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE, StatusCode.STARTED,"Starting to create Resource by user {}",userId); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE, StatusCode.STARTED, "Starting to create Resource by user {}", userId); Response response; try { - Wrapper responseWrapper = new Wrapper<>(); // UI Import if (isUIImport(data)) { @@ -147,20 +142,20 @@ public class ResourcesServlet extends AbstractValidationsServlet { } // UI Create else { - 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(); Resource createdResource = resourceBusinessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null); Object representation = RepresentationUtils.toRepresentation(createdResource); response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); responseWrapper.setInnerElement(response); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog() ,StatusCode.COMPLETE,"Resource successfully created user {}",userId); + loggerSupportability + .log(LoggerSupportabilityActions.CREATE_RESOURCE, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Resource successfully created user {}", userId); } return responseWrapper.getInnerElement(); } catch (final IOException | ZipException e) { @@ -183,36 +178,36 @@ public class ResourcesServlet extends AbstractValidationsServlet { return isUIImport; } - private void performUIImport(final Wrapper responseWrapper, final String data, - final HttpServletRequest request, final String userId, + private void performUIImport(final Wrapper responseWrapper, final String data, final HttpServletRequest request, final String userId, final String resourceUniqueId) throws ZipException { Wrapper userWrapper = new Wrapper<>(); Wrapper uploadResourceInfoWrapper = new Wrapper<>(); Wrapper yamlStringWrapper = new Wrapper<>(); - ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI; - commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, data); - if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { - fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), data, resourceAuthorityEnum, null); - + fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), data, resourceAuthorityEnum, + null); // PayLoad Validations commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); } - specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, data, resourceAuthorityEnum); - + specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, + data, resourceAuthorityEnum); if (responseWrapper.isEmpty()) { - handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId); + handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), + yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId); } } private Either parseToResource(String resourceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE); + return getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE); } private Either parseToLightResource(String resourceJson, User user) { - Either ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); + 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); @@ -224,7 +219,6 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Path("/resources/{resourceId}") @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) { - String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); // get modifier id @@ -232,22 +226,19 @@ public class ResourcesServlet extends AbstractValidationsServlet { User modifier = new User(); modifier.setUserId(userId); log.debug(MODIFIER_ID_IS, userId); - loggerSupportability.log(LoggerSupportabilityActions.DELETE_RESOURCE ,StatusCode.STARTED,"Starting to delete Resource by user {}",userId); + loggerSupportability.log(LoggerSupportabilityActions.DELETE_RESOURCE, StatusCode.STARTED, "Starting to delete Resource by user {}", userId); Response response; - try { String resourceIdLower = resourceId.toLowerCase(); ResponseFormat actionResponse = resourceBusinessLogic.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); - loggerSupportability.log(LoggerSupportabilityActions.DELETE_RESOURCE ,StatusCode.COMPLETE,"Ended delete Resource by user {}",userId); + loggerSupportability.log(LoggerSupportabilityActions.DELETE_RESOURCE, StatusCode.COMPLETE, "Ended delete Resource by user {}", userId); return response; - } catch (JSONException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); log.debug("delete resource failed with exception", e); @@ -257,31 +248,26 @@ public class ResourcesServlet extends AbstractValidationsServlet { @DELETE @Path("/resources/{resourceName}/{version}") - @Operation(description = "Delete Resource By Name And Version", method = "DELETE", summary = "Returns no content", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "204", description = "Resource deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Resource not found")}) + @Operation(description = "Delete Resource By Name And Version", method = "DELETE", summary = "Returns no content", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "204", description = "Resource deleted"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Resource not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { - + 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; 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); @@ -295,33 +281,25 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Path("/resources/{resourceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Resource found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found")}) + @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Resource found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getResourceById(@PathParam("resourceId") final String resourceId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { - + public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { 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 = resourceId.toLowerCase(); log.trace("get resource with id {}", resourceId); Either actionResponse = resourceBusinessLogic.getResource(resourceIdLower, modifier); - if (actionResponse.isRight()) { log.debug("failed to get resource"); response = buildErrorResponse(actionResponse.right().value()); @@ -329,7 +307,6 @@ public class ResourcesServlet extends AbstractValidationsServlet { } Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - } catch (IOException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource"); log.debug("get resource failed with exception", e); @@ -341,31 +318,28 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Resource by name and version", method = "GET", - summary = "Returns resource according to resourceId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Resource found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Resource not found")}) + @Operation(description = "Retrieve Resource by name and version", method = "GET", summary = "Returns resource according to resourceId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Resource found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Resource not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) throws IOException { - // get modifier id User modifier = new User(); modifier.setUserId(userId); log.debug(MODIFIER_ID_IS, userId); Response response; try { - Either actionResponse = resourceBusinessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId); + Either actionResponse = resourceBusinessLogic + .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 (IOException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version"); log.debug("get resource failed with exception", e); @@ -377,36 +351,30 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Path("/resources/validate-name/{resourceName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "validate resource name", method = "GET", - summary = "checks if the chosen resource name is available ", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Resource found"), - @ApiResponse(responseCode = "403", description = "Restricted operation")}) + @Operation(description = "validate resource name", method = "GET", summary = "checks if the chosen resource name is available ", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Resource found"), @ApiResponse(responseCode = "403", description = "Restricted operation")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response validateResourceName(@PathParam("resourceName") final String resourceName, - @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { 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; - 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 = resourceBusinessLogic.validateResourceNameExists(resourceName, typeEnum, userId); - + Either, ResponseFormat> actionResponse = resourceBusinessLogic + .validateResourceNameExists(resourceName, typeEnum, userId); if (actionResponse.isRight()) { log.debug("failed to validate resource name"); response = buildErrorResponse(actionResponse.right().value()); @@ -420,14 +388,13 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}" , url); + log.debug("(get) Start handle request of {}", url); try { - List resources = resourceBusinessLogic - .getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId); + List resources = resourceBusinessLogic.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(resources)); - } catch (IOException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources"); log.debug("getCertifiedAbstractResources failed with exception", e); @@ -440,39 +407,36 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}" , url); + log.debug("(get) Start handle request of {}", url); try { List resouces = resourceBusinessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(resouces)); - } catch (IOException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources"); log.debug("getCertifiedNotAbstractResources failed with exception", e); throw e; } - } @PUT @Path("/resources/{resourceId}/metadata") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Resource Metadata", method = "PUT", summary = "Returns updated resource metadata", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Resource metadata updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content")}) + @Operation(description = "Update Resource Metadata", method = "PUT", summary = "Returns updated resource metadata", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Resource metadata updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId, - @Parameter(description = "Resource metadata to be updated", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { - + @Parameter(description = "Resource metadata to be updated", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - // get modifier id User modifier = new User(); modifier.setUserId(userId); @@ -480,13 +444,16 @@ public class ResourcesServlet extends AbstractValidationsServlet { Response response; try { String resourceIdLower = resourceId.toLowerCase(); - Either updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); + 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; } - Resource updatedResource = resourceBusinessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false); + Resource updatedResource = resourceBusinessLogic + .updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false); Object resource = RepresentationUtils.toRepresentation(updatedResource); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); } catch (IOException e) { @@ -501,17 +468,15 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Update Resource", method = "PUT", summary = "Returns updated resource", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "200", description = "Resource updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Resource already exist")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Resource updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Resource already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateResource( - @Parameter(description = "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) throws IOException, ZipException { - + public Response updateResource(@Parameter(description = "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) throws IOException, ZipException { userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); init(); String url = request.getMethod() + " " + request.getRequestURI(); @@ -520,7 +485,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { User modifier = new User(); modifier.setUserId(userId); log.debug(MODIFIER_ID_IS, userId); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE,StatusCode.STARTED,"Starting to update a resource by user {}",userId); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.STARTED, "Starting to update a resource by user {}", userId); Response response; try { Wrapper responseWrapper = new Wrapper<>(); @@ -534,12 +499,14 @@ public class ResourcesServlet extends AbstractValidationsServlet { response = buildErrorResponse(convertResponse.right().value()); return response; } - Resource updatedResource = resourceBusinessLogic.validateAndUpdateResourceFromCsar(convertResponse.left().value(), modifier, null, null, resourceId); + Resource updatedResource = resourceBusinessLogic + .validateAndUpdateResourceFromCsar(convertResponse.left().value(), modifier, null, null, resourceId); Object representation = RepresentationUtils.toRepresentation(updatedResource); response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); responseWrapper.setInnerElement(response); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE,updatedResource.getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"Ended update a resource by user {}",userId); - + loggerSupportability + .log(LoggerSupportabilityActions.UPDATE_RESOURCE, updatedResource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Ended update a resource by user {}", userId); } return responseWrapper.getInnerElement(); } catch (final IOException | ZipException e) { @@ -553,36 +520,26 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Path("/resources/csar/{csaruuid}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Create Resource", method = "POST", summary = "Returns resource created from csar uuid", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "201", description = "Resource retrieced"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Create Resource", method = "POST", summary = "Returns resource created from csar uuid", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "201", description = "Resource retrieced"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getResourceFromCsar(@Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @PathParam(value = "csaruuid") String csarUUID) throws IOException { - + public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @PathParam(value = "csaruuid") String csarUUID) throws IOException { init(); - 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; - try { - - Either eitherResource = - resourceBusinessLogic.getLatestResourceFromCsarUuid(ValidationUtils.sanitizeInputString(csarUUID), user); - + Either eitherResource = resourceBusinessLogic + .getLatestResourceFromCsarUuid(ValidationUtils.sanitizeInputString(csarUUID), user); // validate response if (eitherResource.isRight()) { log.debug("failed to get resource from csarUuid : {}", csarUUID); @@ -591,9 +548,7 @@ public class ResourcesServlet extends AbstractValidationsServlet { Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value()); response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); } - return response; - } catch (IOException e) { log.debug("get resource by csar failed with exception", e); throw e; @@ -604,48 +559,33 @@ public class ResourcesServlet extends AbstractValidationsServlet { @Path("/resources/importReplaceResource") @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Import Resource", method = "POST", summary = "Returns imported resource", responses = { - @ApiResponse(responseCode = "201", description = "Resource created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Resource already exist")}) + @ApiResponse(responseCode = "201", description = "Resource created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Resource already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response importReplaceResource( - @Parameter(description = "The user id", - required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Context final HttpServletRequest request, - @Parameter(description = "FileInputStream") - @FormDataParam("resourceZip") File file, - @Parameter(description = "ContentDisposition") - @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader, - @Parameter(description = "resourceMetadata") - @FormDataParam("resourceZipMetadata") String resourceInfoJsonString) { - + @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Context final HttpServletRequest request, @Parameter(description = "FileInputStream") @FormDataParam("resourceZip") File file, + @Parameter(description = "ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader, + @Parameter(description = "resourceMetadata") @FormDataParam("resourceZipMetadata") String resourceInfoJsonString) { init(); - String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; log.debug("importReplaceResource,Start handle request of {}", url); - // get modifier id User modifier = new User(); modifier.setUserId(userId); log.debug("importReplaceResource,modifier id is {}", userId); - log.debug("importReplaceResource,get file:{},fileName:{}", file, file.getName()); - Response response; ResponseFormat responseFormat = null; AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Resource; String assetType = "resources"; - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue()); DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI); @@ -653,37 +593,28 @@ public class ResourcesServlet extends AbstractValidationsServlet { if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { log.debug("importReplaceResource: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, null); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, null); return buildErrorResponse(responseFormat); } - try { Wrapper responseWrapper = new Wrapper<>(); // file import Wrapper userWrapper = new Wrapper<>(); Wrapper uploadResourceInfoWrapper = new Wrapper<>(); Wrapper yamlStringWrapper = new Wrapper<>(); - ResourceAuthorityTypeEnum serviceAuthorityEnum = ResourceAuthorityTypeEnum.CSAR_TYPE_BE; - // PayLoad Validations commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, serviceAuthorityEnum, userId, resourceInfoJsonString); - fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, modifier, resourceInfoJsonString, serviceAuthorityEnum, file); - - specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, serviceAuthorityEnum); - + specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), + request, resourceInfoJsonString, serviceAuthorityEnum); log.debug("importReplaceResource:get payload:{}", uploadResourceInfoWrapper.getInnerElement().getPayloadData()); - - log.debug("importReplaceResource:get ResourceType:{}", - uploadResourceInfoWrapper.getInnerElement().getResourceType()); - + log.debug("importReplaceResource:get ResourceType:{}", uploadResourceInfoWrapper.getInnerElement().getResourceType()); if (responseWrapper.isEmpty()) { log.debug("importReplaceService:start handleImport"); - handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null); + handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), + yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null); } - return responseWrapper.getInnerElement(); } catch (ZipException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Resource"); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceConsumptionServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceConsumptionServlet.java index 359050c9a8..27117fa3e4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceConsumptionServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceConsumptionServlet.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.servlets; +import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF; + import com.google.gson.Gson; import com.google.gson.JsonParseException; import com.jcabi.aspects.Loggable; @@ -29,6 +30,26 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +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 java.util.stream.Collectors; +import javax.inject.Inject; +import javax.inject.Singleton; +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.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; @@ -45,39 +66,16 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.OperationInput; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.types.ServiceConsumptionData; import org.openecomp.sdc.be.types.ServiceConsumptionSource; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -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.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.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Tags({@Tag(name = "SDC Internal APIs")}) @@ -91,8 +89,7 @@ public class ServiceConsumptionServlet extends BeGenericServlet { @Inject public ServiceConsumptionServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, - InterfaceOperationBusinessLogic interfaceOperationBusinessLogic, - ServiceBusinessLogic serviceBusinessLogic) { + InterfaceOperationBusinessLogic interfaceOperationBusinessLogic, ServiceBusinessLogic serviceBusinessLogic) { super(userBusinessLogic, componentsUtils); this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic; this.serviceBusinessLogic = serviceBusinessLogic; @@ -102,55 +99,44 @@ public class ServiceConsumptionServlet extends BeGenericServlet { @Path("/services/{serviceId}/consumption/{serviceInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @io.swagger.v3.oas.annotations.Operation(description = "Service consumption on operation", method = "POST", - summary = "Returns consumption data", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Service property created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Service property already exist")}) + @io.swagger.v3.oas.annotations.Operation(description = "Service consumption on operation", method = "POST", summary = "Returns consumption data", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Service property created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Service property already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response addInputToServiceOperation(@PathParam("serviceId") final String serviceId, - @PathParam("serviceInstanceId") final String serviceInstanceId, - @Parameter(description = "Service Consumption Data", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); - User modifier = new User(); - modifier.setUserId(userId); - - try { - - Either>, ResponseFormat> dataFromJson = - getServiceConsumptionData(data, modifier); - if(dataFromJson.isRight()) { - return buildErrorResponse(dataFromJson.right().value()); - } - - Map> serviceConsumptionDataMap = dataFromJson.left().value(); - - for(Entry> consumptionEntry : serviceConsumptionDataMap.entrySet()) { - List consumptionList = consumptionEntry.getValue(); - Either, ResponseFormat> operationEither = - serviceBusinessLogic.addServiceConsumptionData(serviceId, serviceInstanceId, - consumptionEntry.getKey(), consumptionList, userId); - if (operationEither.isRight()) { - return buildErrorResponse(operationEither.right().value()); + @PathParam("serviceInstanceId") final String serviceInstanceId, + @Parameter(description = "Service Consumption Data", required = true) String data, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); + User modifier = new User(); + modifier.setUserId(userId); + try { + Either>, ResponseFormat> dataFromJson = getServiceConsumptionData(data, modifier); + if (dataFromJson.isRight()) { + return buildErrorResponse(dataFromJson.right().value()); + } + Map> serviceConsumptionDataMap = dataFromJson.left().value(); + for (Entry> consumptionEntry : serviceConsumptionDataMap.entrySet()) { + List consumptionList = consumptionEntry.getValue(); + Either, ResponseFormat> operationEither = serviceBusinessLogic + .addServiceConsumptionData(serviceId, serviceInstanceId, consumptionEntry.getKey(), consumptionList, userId); + if (operationEither.isRight()) { + return buildErrorResponse(operationEither.right().value()); + } + } + return buildOkResponse(serviceConsumptionDataMap); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Operation Inputs"); + log.debug("Create Operation Inputs failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); } - } - - return buildOkResponse(serviceConsumptionDataMap); - } - catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Operation Inputs"); - log.debug("Create Operation Inputs failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } - - } @GET @Path("/services/{serviceId}/consumption/{serviceInstanceId}/interfaces/{interfaceId}/operations/{operationId}/inputs") @@ -158,118 +144,99 @@ public class ServiceConsumptionServlet extends BeGenericServlet { @Produces(MediaType.APPLICATION_JSON) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getInputsListOfOperation(@PathParam("serviceId") final String serviceId, - @PathParam("serviceInstanceId") final String serviceInstanceId, - @PathParam("interfaceId") final String interfaceId, @PathParam("operationId") final String operationId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {}", url, userId); - User user = new User(); - user.setUserId(userId); - - try { - Either, ResponseFormat> inputsEither = - interfaceOperationBusinessLogic.getInputsListForOperation(serviceId, serviceInstanceId, interfaceId, operationId, user); - - if(inputsEither.isRight()) { - return buildErrorResponse(inputsEither.right().value()); - } - - List inputs = inputsEither.left().value(); - return buildOkResponse(updateOperationInputListForUi(inputs, interfaceOperationBusinessLogic)); - } - catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Operation Inputs"); - log.debug("Get Operation Inputs failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); + @PathParam("serviceInstanceId") final String serviceInstanceId, + @PathParam("interfaceId") final String interfaceId, @PathParam("operationId") final String operationId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userId); + User user = new User(); + user.setUserId(userId); + try { + Either, ResponseFormat> inputsEither = interfaceOperationBusinessLogic + .getInputsListForOperation(serviceId, serviceInstanceId, interfaceId, operationId, user); + if (inputsEither.isRight()) { + return buildErrorResponse(inputsEither.right().value()); + } + List inputs = inputsEither.left().value(); + return buildOkResponse(updateOperationInputListForUi(inputs, interfaceOperationBusinessLogic)); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Operation Inputs"); + log.debug("Get Operation Inputs failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } } - } - - private List updateOperationInputListForUi(List inputsList, - InterfaceOperationBusinessLogic interfaceOperationBL) { - List operationInputs = new ArrayList<>(); - for(OperationInputDefinition input : inputsList) { - - String value = input.getValue(); - - // Additional UI mapping needed for other sources - if (StringUtils.isNotBlank(value) - && !ServiceConsumptionSource.STATIC.getSource().equals(input.getSource())) { - uiMappingForOtherSources(value, input); - } - // Add Constraint for UI - OperationInput operationInput = new OperationInput(input); - operationInput.setConstraints(interfaceOperationBL.setInputConstraint(input)); - operationInputs.add(operationInput); - } - - return operationInputs; - } - - private void uiMappingForOtherSources(String value, OperationInputDefinition input) { - try { - Map valueAsMap = (new Gson()).fromJson(value, Map.class); - String toscaFunction = valueAsMap.keySet().iterator().next(); - Object consumptionValueName = valueAsMap.values().iterator().next(); - if(consumptionValueName instanceof List) { - List toscaFunctionList = (List) consumptionValueName; - String consumptionInputValue = null; - if (ToscaFunctions.GET_PROPERTY.getFunctionName().equals(toscaFunction)) { - String propertyValue = toscaFunctionList.stream() - .map(Object::toString) - .filter(val -> !val.equals(SELF)) - .collect(Collectors.joining("_")); - consumptionInputValue = String.valueOf(propertyValue); - } else if (ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName().equals(toscaFunction)) { - //Return full output name - consumptionInputValue = - toscaFunctionList.get(1) + "." + toscaFunctionList.get(2) + "." +toscaFunctionList.get(3); - } - input.setValue(consumptionInputValue); - } else { - input.setValue(String.valueOf(consumptionValueName)); - } - } - catch(JsonParseException ex){ - log.info("This means it is static value for which no changes are needed"); - } - } - - private Either>, ResponseFormat> getServiceConsumptionData(String data, - User user) { - JSONParser parser = new JSONParser(); - Map> serviceConsumptionDataMap = new HashMap<>(); - - try { - JSONArray operationsArray = (JSONArray) parser.parse(data); - Iterator iterator = operationsArray.iterator(); - while (iterator.hasNext()) { - Map next = (Map) iterator.next(); - Entry consumptionEntry = (Entry) next.entrySet().iterator().next(); - String operationId = (String) consumptionEntry.getKey(); - Object value = consumptionEntry.getValue(); - - JSONArray inputsArray = (JSONArray) parser.parse(value.toString()); - serviceConsumptionDataMap.putIfAbsent(operationId, new ArrayList<>()); - for(Object consumptionObject : inputsArray) { - Either serviceDataEither = - getComponentsUtils() - .convertJsonToObjectUsingObjectMapper(consumptionObject.toString(), user, ServiceConsumptionData - .class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); - if(serviceDataEither.isRight()) { - return Either.right(serviceDataEither.right().value()); - } + private List updateOperationInputListForUi(List inputsList, + InterfaceOperationBusinessLogic interfaceOperationBL) { + List operationInputs = new ArrayList<>(); + for (OperationInputDefinition input : inputsList) { + String value = input.getValue(); + // Additional UI mapping needed for other sources + if (StringUtils.isNotBlank(value) && !ServiceConsumptionSource.STATIC.getSource().equals(input.getSource())) { + uiMappingForOtherSources(value, input); + } + // Add Constraint for UI + OperationInput operationInput = new OperationInput(input); + operationInput.setConstraints(interfaceOperationBL.setInputConstraint(input)); + operationInputs.add(operationInput); + } + return operationInputs; + } - serviceConsumptionDataMap.get(operationId).add(serviceDataEither.left().value()); + private void uiMappingForOtherSources(String value, OperationInputDefinition input) { + try { + Map valueAsMap = (new Gson()).fromJson(value, Map.class); + String toscaFunction = valueAsMap.keySet().iterator().next(); + Object consumptionValueName = valueAsMap.values().iterator().next(); + if (consumptionValueName instanceof List) { + List toscaFunctionList = (List) consumptionValueName; + String consumptionInputValue = null; + if (ToscaFunctions.GET_PROPERTY.getFunctionName().equals(toscaFunction)) { + String propertyValue = toscaFunctionList.stream().map(Object::toString).filter(val -> !val.equals(SELF)) + .collect(Collectors.joining("_")); + consumptionInputValue = String.valueOf(propertyValue); + } else if (ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName().equals(toscaFunction)) { + //Return full output name + consumptionInputValue = toscaFunctionList.get(1) + "." + toscaFunctionList.get(2) + "." + toscaFunctionList.get(3); + } + input.setValue(consumptionInputValue); + } else { + input.setValue(String.valueOf(consumptionValueName)); + } + } catch (JsonParseException ex) { + log.info("This means it is static value for which no changes are needed"); } - } } - catch (ParseException e) { - log.info("Conetnt is invalid - {}", data); - return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + + private Either>, ResponseFormat> getServiceConsumptionData(String data, User user) { + JSONParser parser = new JSONParser(); + Map> serviceConsumptionDataMap = new HashMap<>(); + try { + JSONArray operationsArray = (JSONArray) parser.parse(data); + Iterator iterator = operationsArray.iterator(); + while (iterator.hasNext()) { + Map next = (Map) iterator.next(); + Entry consumptionEntry = (Entry) next.entrySet().iterator().next(); + String operationId = (String) consumptionEntry.getKey(); + Object value = consumptionEntry.getValue(); + JSONArray inputsArray = (JSONArray) parser.parse(value.toString()); + serviceConsumptionDataMap.putIfAbsent(operationId, new ArrayList<>()); + for (Object consumptionObject : inputsArray) { + Either serviceDataEither = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(consumptionObject.toString(), user, ServiceConsumptionData.class, + AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + if (serviceDataEither.isRight()) { + return Either.right(serviceDataEither.right().value()); + } + serviceConsumptionDataMap.get(operationId).add(serviceDataEither.left().value()); + } + } + } catch (ParseException e) { + log.info("Conetnt is invalid - {}", data); + return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + return Either.left(serviceConsumptionDataMap); } - return Either.left(serviceConsumptionDataMap); - } } 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 index 253acd5395..652dfa082d 100644 --- 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 @@ -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. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; - import com.google.common.collect.Sets; import com.jcabi.aspects.Loggable; import fj.data.Either; @@ -34,6 +32,23 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.IOException; +import java.util.Collections; +import java.util.Set; +import javax.inject.Inject; +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.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; @@ -58,24 +73,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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.io.IOException; -import java.util.Collections; -import java.util.Set; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog/services/{serviceId}/paths") @Consumes(MediaType.APPLICATION_JSON) @@ -91,11 +88,9 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet { private final ServiceBusinessLogic serviceBusinessLogic; @Inject - public ServiceForwardingPathServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - ServiceBusinessLogic serviceBusinessLogic) { + public ServiceForwardingPathServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, + ServiceBusinessLogic serviceBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.serviceBusinessLogic = serviceBusinessLogic; } @@ -104,56 +99,47 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/") - @Operation(description = "Create Forwarding Path", method = "POST", summary = "Create Forwarding Path", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "201", description = "Create Forwarding Path"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")}) + @Operation(description = "Create Forwarding Path", method = "POST", summary = "Create Forwarding Path", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "201", description = "Create Forwarding Path"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response createForwardingPath( - @Parameter(description = "Forwarding Path to create", required = true) String data, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + public Response createForwardingPath(@Parameter(description = "Forwarding Path to create", required = true) String data, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { return createOrUpdate(data, serviceId, request, userId, false); } - - @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/") @Operation(description = "Update Forwarding Path", method = "PUT", summary = "Update Forwarding Path", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "201", description = "Update Forwarding Path"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "201", description = "Update Forwarding Path"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateForwardingPath( - @Parameter(description = "Update Path to create", required = true) String data, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + public Response updateForwardingPath(@Parameter(description = "Update Path to create", required = true) String data, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { return createOrUpdate(data, serviceId, request, userId, true); } - private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) throws IOException { + private Response createOrUpdate(String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) throws IOException { 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(); - Either convertResponse = parseToService(data, modifier); if (convertResponse.isRight()) { log.debug("failed to parse service"); @@ -161,17 +147,15 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet { return response; } Service updatedService = convertResponse.left().value(); - Service actionResponse ; + Service actionResponse; if (isUpdate) { actionResponse = serviceBusinessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true); } else { actionResponse = serviceBusinessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true); } - Service service = actionResponse; Object result = RepresentationUtils.toRepresentation(service); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (IOException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update"); log.debug("create or update forwarding path with an error", e); @@ -184,42 +168,35 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet { @Produces(MediaType.APPLICATION_JSON) @Path("/{forwardingPathId}") @Operation(description = "Get Forwarding Path", method = "GET", summary = "GET Forwarding Path", responses = { - @ApiResponse(content = @Content( - array = @ArraySchema(schema = @Schema(implementation = ForwardingPathDataDefinition.class)))), - @ApiResponse(responseCode = "201", description = "Get Forwarding Path"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ForwardingPathDataDefinition.class)))), + @ApiResponse(responseCode = "201", description = "Get Forwarding Path"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getForwardingPath( - @Parameter(description = "Forwarding Path to create", required = true) String datax, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + public Response getForwardingPath(@Parameter(description = "Forwarding Path to create", required = true) String datax, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { 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 { - Either serviceResponse = serviceBusinessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + Either serviceResponse = serviceBusinessLogic + .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)); - - + 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); @@ -231,35 +208,28 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{forwardingPathId}") - @Operation(description = "Delete Forwarding Path", method = "DELETE", summary = "Delete Forwarding Path", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "201", description = "Delete Forwarding Path"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")}) + @Operation(description = "Delete Forwarding Path", method = "DELETE", summary = "Delete Forwarding Path", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "201", description = "Delete Forwarding Path"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteForwardingPath( - @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + public Response deleteForwardingPath(@Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId, + @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { 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(); - Set deletedPaths = serviceBusinessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true); Object result = RepresentationUtils.toRepresentation(deletedPaths); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (IOException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths"); log.debug("Delete service paths with an error", e); @@ -267,8 +237,8 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet { } } - private Either parseToService(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant + 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 f0ef7074ea..1affe7592c 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.core.JsonProcessingException; @@ -37,6 +36,26 @@ import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; import java.io.File; import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import javax.inject.Inject; +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.http.HttpStatus; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; @@ -77,27 +96,6 @@ import org.openecomp.sdc.common.zip.exception.ZipException; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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.io.IOException; -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") @Tags({@Tag(name = "SDC Internal APIs")}) @@ -105,22 +103,17 @@ import java.util.Map; @Controller public class ServiceServlet extends AbstractValidationsServlet { - private final ElementBusinessLogic elementBusinessLogic; private static final Logger log = Logger.getLogger(ServiceServlet.class); private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceServlet.class.getName()); - private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; private static final String MODIFIER_ID_IS = "modifier id is {}"; - + private final ElementBusinessLogic elementBusinessLogic; private final ServiceBusinessLogic serviceBusinessLogic; @Inject - public ServiceServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - ServiceBusinessLogic serviceBusinessLogic, - ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic) { + public ServiceServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, + ServletUtils servletUtils, ResourceImportManager resourceImportManager, ServiceBusinessLogic serviceBusinessLogic, + ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.serviceBusinessLogic = serviceBusinessLogic; this.elementBusinessLogic = elementBusinessLogic; @@ -131,68 +124,58 @@ public class ServiceServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Create Service", method = "POST", summary = "Returns created service", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "201", description = "Service created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Service already exist")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Service already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createService(@Parameter(description = "Service object to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { 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); - loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE,StatusCode.STARTED,"Starting to create a service by user {} ",userId); - + loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, StatusCode.STARTED, "Starting to create a service by user {} ", userId); validateNotEmptyBody(data); Either convertResponse = parseToService(data, modifier); if (convertResponse.isRight()) { throw new ByResponseFormatComponentException(convertResponse.right().value()); } - Service service = convertResponse.left().value(); Either actionResponse = serviceBusinessLogic.createService(service, modifier); - if (actionResponse.isRight()) { log.debug("Failed to create service"); throw new ByResponseFormatComponentException(actionResponse.right().value()); } - - loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE,service.getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"Service {} has been created by user {} ",service.getName(), userId ); - + loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, + "Service {} has been created by user {} ", service.getName(), userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); } public Either parseToService(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + 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) - @Operation(description = "validate service name", method = "GET", - summary = "checks if the chosen service name is available ", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Service found"), - @ApiResponse(responseCode = "403", description = "Restricted operation")}) + @Operation(description = "validate service name", method = "GET", summary = "checks if the chosen service name is available ", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response validateServiceName(@PathParam("serviceName") final String serviceName, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { 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 { - Either, ResponseFormat> actionResponse = - serviceBusinessLogic.validateServiceNameExists(serviceName, userId); - + Either, ResponseFormat> actionResponse = serviceBusinessLogic.validateServiceNameExists(serviceName, userId); if (actionResponse.isRight()) { log.debug("failed to get validate service name"); return buildErrorResponse(actionResponse.right().value()); @@ -209,20 +192,18 @@ public class ServiceServlet extends AbstractValidationsServlet { @Path("/audit-records/{componentType}/{componentUniqueId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "get component audit records", method = "GET", - summary = "get audit records for a service or a resource", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Service found"), - @ApiResponse(responseCode = "403", description = "Restricted operation")}) + @Operation(description = "get component audit records", method = "GET", summary = "get audit records for a service or a resource", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) { + @PathParam("componentUniqueId") final String componentUniqueId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { init(); 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); @@ -232,14 +213,13 @@ public class ServiceServlet extends AbstractValidationsServlet { Wrapper userWrapper = new Wrapper<>(); try { validateUserExist(responseWrapper, userWrapper, userId); - if (responseWrapper.isEmpty()) { - fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), validateComponentType(componentType), componentUniqueId, context); + fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), validateComponentType(componentType), + componentUniqueId, context); } - if (responseWrapper.isEmpty()) { - Either>, ResponseFormat> eitherServiceAudit = serviceBusinessLogic.getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId); - + Either>, ResponseFormat> eitherServiceAudit = serviceBusinessLogic + .getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId); if (eitherServiceAudit.isRight()) { Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value()); responseWrapper.setInnerElement(errorResponse); @@ -247,10 +227,8 @@ public class ServiceServlet extends AbstractValidationsServlet { 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); @@ -259,8 +237,8 @@ public class ServiceServlet extends AbstractValidationsServlet { return responseWrapper.getInnerElement(); } - private void fillUUIDAndVersion(Wrapper responseWrapper, Wrapper uuidWrapper, Wrapper versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) { - + 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()) { @@ -269,7 +247,6 @@ public class ServiceServlet extends AbstractValidationsServlet { } else { responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value())); } - } else { Either eitherService = getServiceBL(context).getService(componentUniqueId, user); if (eitherService.isLeft()) { @@ -277,7 +254,6 @@ public class ServiceServlet extends AbstractValidationsServlet { versionWrapper.setInnerElement(eitherService.left().value().getVersion()); } else { responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value())); - } } } @@ -285,17 +261,15 @@ public class ServiceServlet extends AbstractValidationsServlet { @DELETE @Path("/services/{serviceId}") @Operation(description = "Delete Service", method = "DELETE", summary = "Return no content", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "204", description = "Service deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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(); @@ -303,16 +277,18 @@ public class ServiceServlet extends AbstractValidationsServlet { log.debug(MODIFIER_ID_IS, userId); try { String serviceIdLower = serviceId.toLowerCase(); - loggerSupportability.log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.STARTED,"Starting to delete service {} by user {} ",serviceIdLower, userId); + loggerSupportability + .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.STARTED, "Starting to delete service {} by user {} ", serviceIdLower, + userId); ServiceBusinessLogic businessLogic = getServiceBL(context); ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier); if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { log.debug("failed to delete service"); return buildErrorResponse(actionResponse); } - loggerSupportability.log(LoggerSupportabilityActions.DELETE_SERVICE,StatusCode.COMPLETE,"Ended deleting service {} by user {}",serviceIdLower, userId); + loggerSupportability + .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.COMPLETE, "Ended deleting service {} by user {}", serviceIdLower, userId); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); log.debug("delete service failed with exception", e); @@ -322,22 +298,17 @@ public class ServiceServlet extends AbstractValidationsServlet { @DELETE @Path("/services/{serviceName}/{version}") - @Operation(description = "Delete Service By Name And Version", method = "DELETE", summary = "Returns no content", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), - @ApiResponse(responseCode = "204", description = "Service deleted"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @Operation(description = "Delete Service By Name And Version", method = "DELETE", summary = "Returns no content", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, - @PathParam("version") final String version, + public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { User modifier = getUser(request); - try { ResponseFormat actionResponse = serviceBusinessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier); - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { log.debug("failed to delete service"); return buildErrorResponse(actionResponse); @@ -353,7 +324,6 @@ public class ServiceServlet extends AbstractValidationsServlet { private User getUser(HttpServletRequest request) { 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(); @@ -366,27 +336,22 @@ public class ServiceServlet extends AbstractValidationsServlet { @Path("/services/{serviceId}/metadata") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "200", description = "Service Updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "200", description = "Service Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId, - @Parameter(description = "Service object to be Updated", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { - + @Parameter(description = "Service object to be Updated", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { 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 { String serviceIdLower = serviceId.toLowerCase(); - Either convertResponse = parseToService(data, modifier); if (convertResponse.isRight()) { log.debug("failed to parse service"); @@ -394,25 +359,24 @@ public class ServiceServlet extends AbstractValidationsServlet { } Service updatedService = convertResponse.left().value(); Either actionResponse = serviceBusinessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier); - if (actionResponse.isRight()) { log.debug("failed to update service"); return buildErrorResponse(actionResponse.right().value()); } - 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); throw e; } } + /** - * updates group instance property values - * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated + * 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 @@ -425,48 +389,46 @@ public class ServiceServlet extends AbstractValidationsServlet { @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Update Group Instance Property Values", method = "PUT", - summary = "Returns updated group instance", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @Operation(description = "Update Group Instance Property Values", method = "PUT", summary = "Returns updated group instance", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId, - @PathParam("componentInstanceId") final String componentInstanceId, - @PathParam("groupInstanceId") final String groupInstanceId, - @Parameter(description = "Group instance object to be Updated", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws JsonProcessingException { - + @PathParam("componentInstanceId") final String componentInstanceId, + @PathParam("groupInstanceId") final String groupInstanceId, + @Parameter(description = "Group instance object to be Updated", required = true) String data, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws JsonProcessingException { 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); - + log.debug(MODIFIER_ID_IS, userId); Either, ResponseFormat> actionResponse = null; try { List updatedProperties; - Type listType = new TypeToken>(){}.getType(); + 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){ + if (actionResponse == null) { log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId); - actionResponse = serviceBusinessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties); - if(actionResponse.isRight()){ + actionResponse = serviceBusinessLogic + .updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties); + if (actionResponse.isRight()) { actionResponse = Either.right(actionResponse.right().value()); } } - if(actionResponse.isLeft()){ + if (actionResponse.isLeft()) { updatedProperties = actionResponse.left().value(); ObjectMapper mapper = new ObjectMapper(); String result = mapper.writeValueAsString(updatedProperties); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } - else{ + } else { return buildErrorResponse(actionResponse.right().value()); } } catch (Exception e) { @@ -479,39 +441,30 @@ public class ServiceServlet extends AbstractValidationsServlet { @Path("/services/{serviceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "200", description = "Service found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getServiceById(@PathParam("serviceId") final String serviceId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { - + public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { 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 { String serviceIdLower = serviceId.toLowerCase(); log.debug("get service with id {}", serviceId); Either actionResponse = serviceBusinessLogic.getService(serviceIdLower, modifier); - if (actionResponse.isRight()) { log.debug("failed to get service"); return buildErrorResponse(actionResponse.right().value()); } - 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); @@ -523,34 +476,26 @@ public class ServiceServlet extends AbstractValidationsServlet { @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Service", method = "GET", - summary = "Returns service according to name and version", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), - @ApiResponse(responseCode = "200", description = "Service found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to name and version", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))), + @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) 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) throws IOException { - + @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { // get modifier id User modifier = new User(); modifier.setUserId(userId); log.debug(MODIFIER_ID_IS, userId); - try { Either actionResponse = serviceBusinessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId); - if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } - 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); @@ -562,25 +507,21 @@ public class ServiceServlet extends AbstractValidationsServlet { @Path("/services/{serviceId}/distribution/{env}/activate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution", - responses = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "409", - description = "Service cannot be distributed due to missing deployment artifacts"), - @ApiResponse(responseCode = "404", description = "Requested service was not found"), - @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")}) + @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution", responses = { + @ApiResponse(responseCode = "200", description = "OK"), + @ApiResponse(responseCode = "409", description = "Service cannot be distributed due to missing deployment artifacts"), + @ApiResponse(responseCode = "404", description = "Requested service was not found"), + @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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) throws IOException { - + 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) + throws IOException { 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); - Either distResponse = serviceBusinessLogic.activateDistribution(serviceId, env, modifier, request); - if (distResponse.isRight()) { log.debug("failed to activate service distribution"); return buildErrorResponse(distResponse.right().value()); @@ -601,29 +542,24 @@ public class ServiceServlet extends AbstractValidationsServlet { @Path("/services/{serviceId}/distribution/{did}/markDeployed") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Mark distribution as deployed", method = "POST", - summary = "relevant audit record will be created", - responses = {@ApiResponse(responseCode = "200", description = "Service was marked as deployed"), - @ApiResponse(responseCode = "409", description = "Restricted operation"), - @ApiResponse(responseCode = "403", description = "Service is not available"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Requested service was not found"), - @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")}) + @Operation(description = "Mark distribution as deployed", method = "POST", summary = "relevant audit record will be created", responses = { + @ApiResponse(responseCode = "200", description = "Service was marked as deployed"), + @ApiResponse(responseCode = "409", description = "Restricted operation"), + @ApiResponse(responseCode = "403", description = "Service is not available"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Requested service was not found"), + @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - 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) throws IOException { - + 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) throws IOException { 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 { Either distResponse = serviceBusinessLogic.markDistributionAsDeployed(serviceId, did, modifier); - if (distResponse.isRight()) { log.debug("failed to mark distribution as deployed"); return buildErrorResponse(distResponse.right().value()); @@ -643,22 +579,20 @@ public class ServiceServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(responses = {@ApiResponse(responseCode = "200", description = "OK"), - @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")}) + @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + 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); - try { Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value(); - Either res = serviceBusinessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED); - + Either res = serviceBusinessLogic + .updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED); if (res.isRight()) { buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -670,45 +604,34 @@ public class ServiceServlet extends AbstractValidationsServlet { } } - @GET @Path("/services/{serviceId}/linksMap") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve Service component relations map", method = "GET", - summary = "Returns service components relations", responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))), - @ApiResponse(responseCode = "200", description = "Service found"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "404", description = "Service not found")}) + @Operation(description = "Retrieve Service component relations map", method = "GET", summary = "Returns service components relations", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))), + @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Service not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, - @Context final HttpServletRequest request, + public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { - 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 { String serviceIdLower = serviceId.toLowerCase(); log.debug("get service components relations with id {}", serviceId); Either actionResponse = serviceBusinessLogic.getServiceComponentsRelations(serviceIdLower, modifier); - if (actionResponse.isRight()) { log.debug("failed to get service relations data"); return buildErrorResponse(actionResponse.right().value()); } - 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); @@ -721,23 +644,21 @@ public class ServiceServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = { - @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), @ApiResponse(responseCode = "409", description = "Service already exist")}) - public Response importNsService(@Parameter(description = "Service object to be imported", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Service already exist")}) + public Response importNsService(@Parameter(description = "Service object to be imported", 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); initSpringFromContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - + 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 { - Wrapper responseWrapper = new Wrapper<>(); performUIImport(responseWrapper, data, request, userId, null); return responseWrapper.getInnerElement(); @@ -749,25 +670,23 @@ public class ServiceServlet extends AbstractValidationsServlet { } } - private void performUIImport(Wrapper responseWrapper, String data, final HttpServletRequest request, String userId, String ServiceUniqueId) - throws FileNotFoundException, ZipException { - + private void performUIImport(Wrapper responseWrapper, String data, final HttpServletRequest request, String userId, + String ServiceUniqueId) throws FileNotFoundException, ZipException { Wrapper userWrapper = new Wrapper<>(); Wrapper uploadServiceInfoWrapper = new Wrapper<>(); Wrapper yamlStringWrapper = new Wrapper<>(); - ServiceAuthorityTypeEnum ServiceAuthorityEnum = ServiceAuthorityTypeEnum.USER_TYPE_UI; - commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, ServiceAuthorityEnum, userId, data); - - specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, data, ServiceAuthorityEnum); - + specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, + data, ServiceAuthorityEnum); if (responseWrapper.isEmpty()) { - handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), ServiceAuthorityEnum, true, ServiceUniqueId); + handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), + yamlStringWrapper.getInnerElement(), ServiceAuthorityEnum, true, ServiceUniqueId); } } - /**import ReplaceService + /** + * import ReplaceService * * @param userId * @param requestId @@ -785,61 +704,41 @@ public class ServiceServlet extends AbstractValidationsServlet { @Path("/services/serviceUUID/{uuid}/importReplaceService") @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = { - @ApiResponse(responseCode = "201", description = "Service created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Service already exist")}) + @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Service already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response importReplaceService( - @Parameter(description = "The user id", - required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Parameter(description = "X-ECOMP-RequestID header", - required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam( - value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @Parameter(description = "Determines the format of the body of the response", - required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @Parameter(description = "The username and password", - required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @Context final HttpServletRequest request, - @Parameter(description = "FileInputStream") - @FormDataParam("serviceZip") File file, - @Parameter(description = "ContentDisposition") - @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader, - @Parameter(description = "serviceMetadata") - @FormDataParam("serviceZipMetadata") String serviceInfoJsonString, - @Parameter(description = "The requested asset uuid", - required = true) @PathParam("uuid") final String uuid) { - + @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @Context final HttpServletRequest request, @Parameter(description = "FileInputStream") @FormDataParam("serviceZip") File file, + @Parameter(description = "ContentDisposition") @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader, + @Parameter(description = "serviceMetadata") @FormDataParam("serviceZipMetadata") String serviceInfoJsonString, + @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) { initSpringFromContext(); - String requestURI = request.getRequestURI(); String url = request.getMethod() + " " + requestURI; log.debug("importReplaceService,Start handle request of {}", url); - // get modifier id User modifier = new User(); modifier.setUserId(userId); log.debug("importReplaceService,modifier id is {}", userId); - - log.debug("importReplaceService,get file:{},fileName:{}",file,file.getName()); - + log.debug("importReplaceService,get file:{},fileName:{}", file, file.getName()); Response response; - ResponseFormat responseFormat =null; + ResponseFormat responseFormat = null; AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Service; String assetType = "services"; - - Either, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); - + Either, ResponseFormat> assetTypeData = elementBusinessLogic + .getCatalogComponentsByUuidAndAssetType(assetType, uuid); if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) { log.debug("getServiceAbstractStatus: Service Fetching Failed"); throw new ByResponseFormatComponentException(assetTypeData.right().value()); } - log.debug("getServiceAbstractStatus: Service Fetching Success"); - Service oldService = (Service) assetTypeData.left().value().get(0); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue()); DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI); @@ -847,43 +746,36 @@ public class ServiceServlet extends AbstractValidationsServlet { if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { log.debug("importReplaceService: Missing X-ECOMP-InstanceID header"); responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, - resourceCommonInfo, requestId, null); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, null); return buildErrorResponse(responseFormat); } - try { Wrapper responseWrapper = new Wrapper<>(); // file import Wrapper userWrapper = new Wrapper<>(); Wrapper uploadServiceInfoWrapper = new Wrapper<>(); Wrapper yamlStringWrapper = new Wrapper<>(); - ServiceUploadServlet.ServiceAuthorityTypeEnum serviceAuthorityEnum = ServiceUploadServlet.ServiceAuthorityTypeEnum.CSAR_TYPE_BE; - // PayLoad Validations - commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId, serviceInfoJsonString); - - fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum, file); - - specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, serviceInfoJsonString, serviceAuthorityEnum); - + commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId, + serviceInfoJsonString); + fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum, + file); + specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, + serviceInfoJsonString, serviceAuthorityEnum); log.debug("importReplaceService:get payload:{}", uploadServiceInfoWrapper.getInnerElement().getPayloadData()); - - ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition)oldService.getComponentMetadataDefinition().getMetadataDataDefinition(); - + ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) oldService.getComponentMetadataDefinition() + .getMetadataDataDefinition(); uploadServiceInfoWrapper.getInnerElement().setServiceVendorModelNumber(serviceMetadataDataDefinition.getServiceVendorModelNumber()); uploadServiceInfoWrapper.getInnerElement().setDescription(oldService.getDescription()); uploadServiceInfoWrapper.getInnerElement().setCategories(oldService.getCategories()); uploadServiceInfoWrapper.getInnerElement().setIcon(oldService.getIcon()); uploadServiceInfoWrapper.getInnerElement().setProjectCode(oldService.getProjectCode()); - - if (responseWrapper.isEmpty()) { log.debug("importReplaceService:start handleImportService"); - handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null); + handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), + yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null); } - return responseWrapper.getInnerElement(); } catch (IOException | ZipException e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service"); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceUploadServlet.java index 285568560d..20a259dad6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceUploadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceUploadServlet.java @@ -17,52 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.servers.Server; -import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import java.io.File; 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 org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; -import org.openecomp.sdc.be.components.impl.ServiceImportManager; -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.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.UploadServiceInfo; -import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Controller; -import org.springframework.web.context.WebApplicationContext; /** * Root service (exposed at "/" path) @@ -73,29 +40,31 @@ import org.springframework.web.context.WebApplicationContext; @Path("/v1/catalog/uploadservice") @Tags({@Tag(name = "SDC Internal APIs")}) @Singleton - public class ServiceUploadServlet extends AbstractValidationsServlet { - private static final Logger log = Logger.getLogger(ServiceUploadServlet.class); public static final String NORMATIVE_TYPE_SERVICE = "multipart"; public static final String CSAR_TYPE_SERVICE = "csar"; public static final String USER_TYPE_SERVICE = "user-service"; public static final String USER_TYPE_SERVICE_UI_IMPORT = "user-servcie-ui-import"; + private static final Logger log = Logger.getLogger(ServiceUploadServlet.class); - public ServiceUploadServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager) { + public ServiceUploadServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); } public enum ServiceAuthorityTypeEnum { - NORMATIVE_TYPE_BE(NORMATIVE_TYPE_SERVICE, true, false), USER_TYPE_BE(USER_TYPE_SERVICE, true, true), - USER_TYPE_UI(USER_TYPE_SERVICE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_SERVICE, true, true); - + NORMATIVE_TYPE_BE(NORMATIVE_TYPE_SERVICE, true, false), USER_TYPE_BE(USER_TYPE_SERVICE, true, true), USER_TYPE_UI(USER_TYPE_SERVICE_UI_IMPORT, + false, true), CSAR_TYPE_BE(CSAR_TYPE_SERVICE, true, true); private String urlPath; private boolean isBackEndImport, isUserTypeService; + private ServiceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeService) { + this.urlPath = urlPath; + this.isBackEndImport = isBackEndImport; + this.isUserTypeService = isUserTypeService; + } + public static ServiceAuthorityTypeEnum findByUrlPath(String urlPath) { ServiceAuthorityTypeEnum found = null; for (ServiceAuthorityTypeEnum curr : ServiceAuthorityTypeEnum.values()) { @@ -107,12 +76,6 @@ public class ServiceUploadServlet extends AbstractValidationsServlet { return found; } - private ServiceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeService) { - this.urlPath = urlPath; - this.isBackEndImport = isBackEndImport; - this.isUserTypeService = isUserTypeService; - } - public String getUrlPath() { return urlPath; } @@ -126,4 +89,3 @@ public class ServiceUploadServlet extends AbstractValidationsServlet { } } } - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TogglingServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TogglingServlet.java index df53919b59..884cbcc1e3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TogglingServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TogglingServlet.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -59,36 +58,31 @@ import org.openecomp.sdc.common.log.wrappers.Logger; @Singleton public class TogglingServlet extends AbstractValidationsServlet { + private static final Logger log = Logger.getLogger(TogglingServlet.class); + private static final String ALL_FEATURES_STATES_WERE_SET_SUCCESSFULLY = "All features states were set successfully"; + private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; + private static final String FEATURE_STATE_WAS_UPDATED_SUCCESSFULLY = "Feature state was updated successfully"; private final TogglingBusinessLogic togglingBusinessLogic; @Inject - public TogglingServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, - TogglingBusinessLogic togglingBusinessLogic) { + public TogglingServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, + ServletUtils servletUtils, ResourceImportManager resourceImportManager, TogglingBusinessLogic togglingBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.togglingBusinessLogic = togglingBusinessLogic; } - private static final Logger log = Logger.getLogger(TogglingServlet.class); - private static final String ALL_FEATURES_STATES_WERE_SET_SUCCESSFULLY = "All features states were set successfully"; - private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; - private static final String FEATURE_STATE_WAS_UPDATED_SUCCESSFULLY = "Feature state was updated successfully"; - - @GET @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Get all Toggleable features", method = "GET", summary = "Returns list of toggleable features", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))), - @ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Toggleable features not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))), + @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Toggleable features not found")}) public Response getAllFeatures(@Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { Map features = togglingBusinessLogic.getAllFeatureStates(); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), features); @@ -102,15 +96,13 @@ public class TogglingServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Get Toggleable feature state", method = "GET", summary = "Returns one toggleable feature state", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))), - @ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Toggleable feature not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))), + @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Toggleable feature not found")}) public Response getToggleableFeature(@PathParam("featureName") String featureName, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { boolean featureState = togglingBusinessLogic.getFeatureState(featureName); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), featureState); @@ -124,15 +116,13 @@ public class TogglingServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Update all feature toggle state", method = "PUT", summary = "Update all feature status", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))), - @ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Toggleable features not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))), + @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Toggleable features not found")}) public Response setAllFeatures(@PathParam("state") boolean state, @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); - try { togglingBusinessLogic.setAllFeatures(state); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ALL_FEATURES_STATES_WERE_SET_SUCCESSFULLY); @@ -146,16 +136,14 @@ public class TogglingServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Update feature toggle state", method = "PUT", summary = "Update feature status", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))), - @ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Toggleable features not found")}) - public Response updateFeatureState(@PathParam("featureName") String featureName, - @PathParam("state") boolean state, @Context final HttpServletRequest request) { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))), + @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Toggleable features not found")}) + public Response updateFeatureState(@PathParam("featureName") String featureName, @PathParam("state") boolean state, + @Context final HttpServletRequest request) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of {}", url); - try { togglingBusinessLogic.updateFeatureState(featureName, state); return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), FEATURE_STATE_WAS_UPDATED_SUCCESSFULLY); @@ -163,6 +151,4 @@ public class TogglingServlet extends AbstractValidationsServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - - } 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 526e0230bb..7683f6961d 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,6 +30,21 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.inject.Inject; +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 org.apache.commons.collections4.ListUtils; import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; @@ -62,23 +76,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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 java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Tags({@Tag(name = "SDC Internal APIs")}) @@ -95,15 +92,10 @@ public class TypesFetchServlet extends AbstractValidationsServlet { private final ResourceBusinessLogic resourceBusinessLogic; @Inject - public TypesFetchServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - PropertyBusinessLogic propertyBusinessLogic, - RelationshipTypeBusinessLogic relationshipTypeBusinessLogic, - CapabilitiesBusinessLogic capabilitiesBusinessLogic, - InterfaceOperationBusinessLogic interfaceOperationBusinessLogic, - ResourceBusinessLogic resourceBusinessLogic) { + public TypesFetchServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, + ServletUtils servletUtils, ResourceImportManager resourceImportManager, PropertyBusinessLogic propertyBusinessLogic, + RelationshipTypeBusinessLogic relationshipTypeBusinessLogic, CapabilitiesBusinessLogic capabilitiesBusinessLogic, + InterfaceOperationBusinessLogic interfaceOperationBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.propertyBusinessLogic = propertyBusinessLogic; this.relationshipTypeBusinessLogic = relationshipTypeBusinessLogic; @@ -117,74 +109,59 @@ public class TypesFetchServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "datatypes"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Data types not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "datatypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Data types not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - Wrapper responseWrapper = new Wrapper<>(); Wrapper userWrapper = new Wrapper<>(); - init(); validateUserExist(responseWrapper, userWrapper, userId); - if (responseWrapper.isEmpty()) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {} - modifier id is {}", url, userId); - Map dataTypes = propertyBusinessLogic.getAllDataTypes(); String dataTypeJson = gson.toJson(dataTypes); Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson); responseWrapper.setInnerElement(okResponse); } - - return responseWrapper.getInnerElement(); - } + return responseWrapper.getInnerElement(); + } @GET @Path("interfaceLifecycleTypes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get interface lifecycle types", method = "GET", - summary = "Returns interface lifecycle types", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Interface lifecycle types"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Interface lifecycle types not found")}) + @Operation(description = "Get interface lifecycle types", method = "GET", summary = "Returns interface lifecycle types", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Interface lifecycle types"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Interface lifecycle types not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - + public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { Wrapper responseWrapper = new Wrapper<>(); Wrapper userWrapper = new Wrapper<>(); - try { validateUserExist(responseWrapper, userWrapper, userId); - if (responseWrapper.isEmpty()) { String url = request.getMethod() + " " + request.getRequestURI(); log.info("Start handle request of {} | modifier id is {}", url, userId); - - Either, ResponseFormat> allInterfaceLifecycleTypes = - interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(); - + Either, ResponseFormat> allInterfaceLifecycleTypes = interfaceOperationBusinessLogic + .getAllInterfaceLifecycleTypes(); if (allInterfaceLifecycleTypes.isRight()) { - log.info("Failed to get all interface lifecycle types. Reason - {}", - allInterfaceLifecycleTypes.right().value()); + log.info("Failed to get all interface lifecycle types. Reason - {}", allInterfaceLifecycleTypes.right().value()); Response errorResponse = buildErrorResponse(allInterfaceLifecycleTypes.right().value()); responseWrapper.setInnerElement(errorResponse); - } else { String interfaceLifecycleTypeJson = gson.toJson(allInterfaceLifecycleTypes.left().value()); Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), interfaceLifecycleTypeJson); responseWrapper.setInnerElement(okResponse); - } } - return responseWrapper.getInnerElement(); } catch (Exception e) { log.debug("get all interface lifecycle types failed with exception", e); @@ -192,50 +169,39 @@ public class TypesFetchServlet extends AbstractValidationsServlet { return buildErrorResponse(responseFormat); } } + @GET @Path("capabilityTypes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Get capability types", method = "GET", summary = "Returns capability types", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "capabilityTypes"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Capability types not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "capabilityTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Capability types not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = - Constants.USER_ID_HEADER) String userId) { - + public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { Wrapper responseWrapper = new Wrapper<>(); Wrapper userWrapper = new Wrapper<>(); - try { init(); validateUserExist(responseWrapper, userWrapper, userId); - if (responseWrapper.isEmpty()) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {} | modifier id is {}", url, userId); - - Either, ResponseFormat> allDataTypes = - capabilitiesBusinessLogic.getAllCapabilityTypes(); - + Either, ResponseFormat> allDataTypes = capabilitiesBusinessLogic.getAllCapabilityTypes(); if (allDataTypes.isRight()) { log.info("Failed to get all capability 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); + Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson); responseWrapper.setInnerElement(okResponse); - } } - return responseWrapper.getInnerElement(); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capability Types"); @@ -249,47 +215,36 @@ public class TypesFetchServlet extends AbstractValidationsServlet { @Path("relationshipTypes") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Get relationship types", method = "GET", summary = "Returns relationship types", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "relationshipTypes"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Relationship types not found")}) + @Operation(description = "Get relationship types", method = "GET", summary = "Returns relationship types", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "relationshipTypes"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Relationship types not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = - Constants.USER_ID_HEADER) String userId) { - + public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { Wrapper responseWrapper = new Wrapper<>(); Wrapper userWrapper = new Wrapper<>(); - try { init(); validateUserExist(responseWrapper, userWrapper, userId); - if (responseWrapper.isEmpty()) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {} | modifier id is {}", url, userId); - - Either, ResponseFormat> allDataTypes = - relationshipTypeBusinessLogic.getAllRelationshipTypes(); - + Either, ResponseFormat> allDataTypes = relationshipTypeBusinessLogic + .getAllRelationshipTypes(); if (allDataTypes.isRight()) { log.info("Failed to get all relationship 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); + Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson); responseWrapper.setInnerElement(okResponse); - } } - return responseWrapper.getInnerElement(); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Relationship Types"); @@ -304,47 +259,37 @@ public class TypesFetchServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Get node types", method = "GET", summary = "Returns node types", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "nodeTypes"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Node types not found")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "nodeTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Node types not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response getAllNodeTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = - Constants.USER_ID_HEADER) String userId) { - + public Response getAllNodeTypesServlet(@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(); Either, Response> response; Map componentMap; - try { init(); validateUserExist(responseWrapper, userWrapper, userId); - if (responseWrapper.isEmpty()) { String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {} | modifier id is {}", url, userId); - response = getComponent(resourceBusinessLogic, true, userId); if (response.isRight()) { return response.right().value(); } componentMap = new HashMap<>(response.left().value()); - response = getComponent(resourceBusinessLogic, false, userId); if (response.isRight()) { return response.right().value(); } componentMap.putAll(response.left().value()); - String nodeTypesJson = gson.toJson(componentMap); - Response okResponse = - buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson); + Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson); responseWrapper.setInnerElement(okResponse); } - return responseWrapper.getInnerElement(); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Node Types"); @@ -354,27 +299,20 @@ public class TypesFetchServlet extends AbstractValidationsServlet { } } - private Either, Response> getComponent(ComponentBusinessLogic resourceBL, boolean isAbstract, - String userId) { + private Either, Response> getComponent(ComponentBusinessLogic resourceBL, boolean isAbstract, String userId) { Either, ResponseFormat> actionResponse; List componentList; - - actionResponse = - resourceBL.getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY - , ComponentTypeEnum.RESOURCE, null, userId); + actionResponse = resourceBL + .getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY, ComponentTypeEnum.RESOURCE, null, userId); if (actionResponse.isRight()) { log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(buildErrorResponse(actionResponse.right().value())); } - componentList = actionResponse.left().value(); - - return Either.left(ListUtils.emptyIfNull(componentList).stream() - .filter(component -> ((ResourceMetadataDataDefinition) component - .getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null) - .collect(Collectors.toMap( - component -> ((ResourceMetadataDataDefinition) component - .getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName(), - component -> component, (component1, component2) -> component1))); + return Either.left(ListUtils.emptyIfNull(componentList).stream().filter(component -> + ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null) + .collect(Collectors.toMap( + component -> ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()) + .getToscaResourceName(), component -> component, (component1, component2) -> component1))); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadEndpoint.java index b0b897daf3..8d3f58e665 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadEndpoint.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadEndpoint.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.google.common.annotations.VisibleForTesting; @@ -32,6 +31,16 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.File; +import java.util.List; +import java.util.Map; +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.MediaType; +import javax.ws.rs.core.Response; import org.apache.commons.lang3.tuple.ImmutablePair; import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.CommonImportManager; @@ -51,16 +60,6 @@ import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; -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.MediaType; -import javax.ws.rs.core.Response; -import java.io.File; -import java.util.List; -import java.util.Map; /** * Here new APIs for types upload written in an attempt to gradually servlet code */ @@ -71,47 +70,21 @@ import java.util.Map; @Tags({@Tag(name = "SDC Internal APIs")}) @Servers({@Server(url = "/sdc2/rest")}) @Controller -public class TypesUploadEndpoint extends BeGenericServlet{ - private static final Logger LOGGER = LoggerFactory.getLogger(TypesUploadEndpoint.class); +public class TypesUploadEndpoint extends BeGenericServlet { + private static final Logger LOGGER = LoggerFactory.getLogger(TypesUploadEndpoint.class); private final CommonImportManager commonImportManager; private final AnnotationTypeOperations annotationTypeOperations; private final AccessValidations accessValidations; - public TypesUploadEndpoint(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, CommonImportManager commonImportManager, AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) { + public TypesUploadEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, CommonImportManager commonImportManager, + AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) { super(userBusinessLogic, componentsUtils); this.commonImportManager = commonImportManager; this.annotationTypeOperations = annotationTypeOperations; this.accessValidations = accessValidations; } - @POST - @Path("/annotationtypes") - @Operation(description = "Create AnnotationTypes from yaml", method = "POST", - summary = "Returns created annotation types", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "annotation types created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "annotation types already exist")}) - @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response uploadAnnotationTypes(@Parameter(description = "FileInputStream") @FormDataParam("annotationTypesZip") File file, - @HeaderParam("USER_ID") String userId) { - accessValidations.validateUserExists(userId, "Annotation Types Creation"); - final Wrapper yamlStringWrapper = new Wrapper<>(); - try { - AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file); - } catch (final ZipException e) { - LOGGER.error("Could not extract zip contents", e); - } - List> typesResults = commonImportManager.createElementTypes(yamlStringWrapper.getInnerElement(), TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations); - HttpStatus status = getHttpStatus(typesResults); - return Response.status(status.value()) - .entity(typesResults) - .build(); - } - @VisibleForTesting static HttpStatus getHttpStatus(List> typesResults) { boolean typeActionFailed = false; @@ -119,7 +92,7 @@ public class TypesUploadEndpoint extends BeGenericServlet{ boolean typeActionSucceeded = false; for (ImmutablePair typeResult : typesResults) { Boolean result = typeResult.getRight(); - if (result==null) { + if (result == null) { typeExists = true; } else if (result) { typeActionSucceeded = true; @@ -129,7 +102,7 @@ public class TypesUploadEndpoint extends BeGenericServlet{ } HttpStatus status = HttpStatus.OK; if (typeActionFailed) { - status = HttpStatus.BAD_REQUEST; + status = HttpStatus.BAD_REQUEST; } else if (typeActionSucceeded) { status = HttpStatus.CREATED; } else if (typeExists) { @@ -148,5 +121,27 @@ public class TypesUploadEndpoint extends BeGenericServlet{ return (T) annotationType; } - + @POST + @Path("/annotationtypes") + @Operation(description = "Create AnnotationTypes from yaml", method = "POST", summary = "Returns created annotation types", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "annotation types created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "annotation types already exist")}) + @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) + public Response uploadAnnotationTypes(@Parameter(description = "FileInputStream") @FormDataParam("annotationTypesZip") File file, + @HeaderParam("USER_ID") String userId) { + accessValidations.validateUserExists(userId, "Annotation Types Creation"); + final Wrapper yamlStringWrapper = new Wrapper<>(); + try { + AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file); + } catch (final ZipException e) { + LOGGER.error("Could not extract zip contents", e); + } + List> typesResults = commonImportManager + .createElementTypes(yamlStringWrapper.getInnerElement(), TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations); + HttpStatus status = getHttpStatus(typesResults); + return Response.status(status.value()).entity(typesResults).build(); + } } 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 953346ee36..9e945d613f 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.google.gson.reflect.TypeToken; @@ -33,6 +32,23 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +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.inject.Inject; +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 org.apache.commons.lang3.tuple.ImmutablePair; import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; @@ -66,24 +82,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.inject.Inject; -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") @Consumes(MediaType.MULTIPART_FORM_DATA) @@ -92,9 +90,9 @@ import java.util.stream.Collectors; @Servers({@Server(url = "/sdc2/rest")}) @Controller public class TypesUploadServlet extends AbstractValidationsServlet { - private static final Logger log = Logger.getLogger(TypesUploadServlet.class); - public static final String CREATE = "Create "; + public static final String CREATE = "Create "; + private static final Logger log = Logger.getLogger(TypesUploadServlet.class); private final CapabilityTypeImportManager capabilityTypeImportManager; private final InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager; private final CategoriesImportManager categoriesImportManager; @@ -104,17 +102,13 @@ public class TypesUploadServlet extends AbstractValidationsServlet { private final RelationshipTypeImportManager relationshipTypeImportManager; @Inject - public TypesUploadServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - CapabilityTypeImportManager capabilityTypeImportManager, - InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager, - CategoriesImportManager categoriesImportManager, - DataTypeImportManager dataTypeImportManager, - GroupTypeImportManager groupTypeImportManager, - PolicyTypeImportManager policyTypeImportManager, - RelationshipTypeImportManager relationshipTypeImportManager) { + public TypesUploadServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager, + CapabilityTypeImportManager capabilityTypeImportManager, + InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager, + CategoriesImportManager categoriesImportManager, DataTypeImportManager dataTypeImportManager, + GroupTypeImportManager groupTypeImportManager, PolicyTypeImportManager policyTypeImportManager, + RelationshipTypeImportManager relationshipTypeImportManager) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.capabilityTypeImportManager = capabilityTypeImportManager; this.interfaceLifecycleTypeImportManager = interfaceLifecycleTypeImportManager; @@ -127,142 +121,124 @@ public class TypesUploadServlet extends AbstractValidationsServlet { @POST @Path("/capability") - @Operation(description = "Create Capability Type from yaml", method = "POST", - summary = "Returns created Capability Type", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Capability Type created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Capability Type already exist")}) + @Operation(description = "Create Capability Type from yaml", method = "POST", summary = "Returns created Capability Type", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Capability Type created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Capability Type already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response uploadCapabilityType(@Parameter(description = "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()); + @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("/relationship") - @Operation(description = "Create Relationship Type from yaml", method = "POST", - summary = "Returns created Relationship Type", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Relationship Type created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Relationship Type already exist")}) + @Operation(description = "Create Relationship Type from yaml", method = "POST", summary = "Returns created Relationship Type", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Relationship Type created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Relationship Type already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response uploadRelationshipType(@Parameter(description = "FileInputStream") @FormDataParam("relationshipTypeZip") File file, - @Context final HttpServletRequest request, - @HeaderParam("USER_ID") String creator) { - return uploadElementTypeServletLogic(this::createRelationshipTypes, file, request, creator, - NodeTypeEnum.RelationshipType.getName()); + @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + return uploadElementTypeServletLogic(this::createRelationshipTypes, file, request, creator, NodeTypeEnum.RelationshipType.getName()); } @POST @Path("/interfaceLifecycle") - @Operation(description = "Create Interface Lyfecycle Type from yaml", method = "POST", - summary = "Returns created Interface Lifecycle Type", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Interface Lifecycle Type created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Interface Lifecycle Type already exist")}) + @Operation(description = "Create Interface Lyfecycle Type from yaml", method = "POST", summary = "Returns created Interface Lifecycle Type", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Interface Lifecycle Type created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Interface Lifecycle Type already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response uploadInterfaceLifecycleType( - @Parameter(description = "FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, - @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - ConsumerTwoParam, String> createElementsMethod = - (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, - () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload)); + public Response uploadInterfaceLifecycleType(@Parameter(description = "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") - @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created categories", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Categories created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Category already exist")}) + @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created categories", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Categories created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Category already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response uploadCategories(@Parameter(description = "FileInputStream") @FormDataParam("categoriesZip") File file, - @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - ConsumerTwoParam, String> createElementsMethod = - (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, - () -> categoriesImportManager.createCategories(ymlPayload)); + @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") - @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created data types", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Data types created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Data types already exist")}) + @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created data types", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Data types created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Data types already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response uploadDataTypes(@Parameter(description = "FileInputStream") @FormDataParam("dataTypesZip") File file, - @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { ConsumerTwoParam, String> createElementsMethod = this::createDataTypes; - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, - NodeTypeEnum.DataType.getName()); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName()); } @POST @Path("/grouptypes") - @Operation(description = "Create GroupTypes from yaml", method = "POST", summary = "Returns created group types", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "group types created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "group types already exist")}) + @Operation(description = "Create GroupTypes from yaml", method = "POST", summary = "Returns created group types", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "group types created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "group types already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response uploadGroupTypes( - @Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData, - @Parameter(description = "FileInputStream") @FormDataParam("groupTypesZip") File file, - @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + public Response uploadGroupTypes(@Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData, + @Parameter(description = "FileInputStream") @FormDataParam("groupTypesZip") File file, + @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { Map typesMetadata = getTypesMetadata(toscaTypesMetaData); - return uploadTypesWithMetaData(this::createGroupTypes, typesMetadata, file, request, creator, - NodeTypeEnum.GroupType.getName()); + return uploadTypesWithMetaData(this::createGroupTypes, typesMetadata, file, request, creator, NodeTypeEnum.GroupType.getName()); } @POST @Path("/policytypes") - @Operation(description = "Create PolicyTypes from yaml", method = "POST", summary = "Returns created policy types", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "policy types created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "policy types already exist")}) + @Operation(description = "Create PolicyTypes from yaml", method = "POST", summary = "Returns created policy types", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "policy types created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "policy types already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response uploadPolicyTypes( - @Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData, - @Parameter(description = "FileInputStream") @FormDataParam("policyTypesZip") File file, - @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + public Response uploadPolicyTypes(@Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData, + @Parameter(description = "FileInputStream") @FormDataParam("policyTypesZip") File file, + @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { Map typesMetadata = getTypesMetadata(toscaTypesMetaData); - return uploadTypesWithMetaData(this::createPolicyTypes, typesMetadata, file, request, creator, - NodeTypeEnum.PolicyType.getName()); + return uploadTypesWithMetaData(this::createPolicyTypes, typesMetadata, file, request, creator, NodeTypeEnum.PolicyType.getName()); } private Map getTypesMetadata(String toscaTypesMetaData) { - return gson.fromJson(toscaTypesMetaData, new TypeToken>(){}.getType()); + return gson.fromJson(toscaTypesMetaData, new TypeToken>() { + }.getType()); } - private Response uploadElementTypeServletLogic(ConsumerTwoParam, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) { + private Response uploadElementTypeServletLogic(ConsumerTwoParam, String> createElementsMethod, File file, + final HttpServletRequest request, String creator, String elementTypeName) { init(); String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER); try { Wrapper yamlStringWrapper = new Wrapper<>(); - String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url); Wrapper responseWrapper = doUploadTypeValidations(request, userId, file); @@ -283,23 +259,21 @@ public class TypesUploadServlet extends AbstractValidationsServlet { private Wrapper doUploadTypeValidations(final HttpServletRequest request, String userId, File file) { Wrapper responseWrapper = new Wrapper<>(); Wrapper userWrapper = 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); } return responseWrapper; } - private Response uploadTypesWithMetaData(ConsumerTwoParam, ToscaTypeImportData> createElementsMethod, Map typesMetaData, File file, final HttpServletRequest request, String creator, String elementTypeName) { + private Response uploadTypesWithMetaData(ConsumerTwoParam, ToscaTypeImportData> createElementsMethod, + Map typesMetaData, File file, final HttpServletRequest request, + String creator, String elementTypeName) { init(); String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER); Wrapper yamlStringWrapper = new Wrapper<>(); @@ -327,7 +301,8 @@ public class TypesUploadServlet extends AbstractValidationsServlet { responseWrapper.setInnerElement(response); } else { try { - Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value())); + 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)); @@ -339,32 +314,33 @@ public class TypesUploadServlet extends AbstractValidationsServlet { // 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()); + 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, ToscaTypeImportData toscaTypeImportData) { - final Supplier>, ResponseFormat>> generateElementTypeFromYml = - () -> groupTypeImportManager.createGroupTypes(toscaTypeImportData); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, - ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name()); + final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager + .createGroupTypes(toscaTypeImportData); + buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, + NodeTypeEnum.GroupType.name()); } // policy types private void createPolicyTypes(Wrapper responseWrapper, ToscaTypeImportData toscaTypeImportData) { - final Supplier>, ResponseFormat>> generateElementTypeFromYml = - () -> policyTypeImportManager.createPolicyTypes(toscaTypeImportData); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, - ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name()); + final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager + .createPolicyTypes(toscaTypeImportData); + 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) { + 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); @@ -374,11 +350,13 @@ public class TypesUploadServlet extends AbstractValidationsServlet { 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)); + Map>> collect = list.stream() + .collect(Collectors.groupingBy(ImmutablePair::getRight)); if (collect != null) { Set keySet = collect.keySet(); if (keySet.size() == 1) { @@ -388,17 +366,14 @@ public class TypesUploadServlet extends AbstractValidationsServlet { 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); @@ -407,12 +382,12 @@ public class TypesUploadServlet extends AbstractValidationsServlet { } } } + // relationship types private void createRelationshipTypes(Wrapper responseWrapper, String relationshipTypesYml) { - final Supplier>, ResponseFormat>> - generateElementTypeFromYml = - () -> relationshipTypeImportManager.createRelationshipTypes(relationshipTypesYml); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, - ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST, NodeTypeEnum.RelationshipType.name()); + final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> relationshipTypeImportManager + .createRelationshipTypes(relationshipTypesYml); + buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST, + NodeTypeEnum.RelationshipType.name()); } } 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 1cd9844331..84a88f3b58 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; @@ -31,18 +30,10 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.eclipse.jetty.http.HttpStatus; -import org.openecomp.sdc.be.components.impl.aaf.AafPermission; -import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.user.Role; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.be.user.UserBusinessLogicExt; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.springframework.stereotype.Controller; - +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -56,10 +47,18 @@ 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.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.List; +import org.eclipse.jetty.http.HttpStatus; +import org.openecomp.sdc.be.components.impl.aaf.AafPermission; +import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.be.user.UserBusinessLogicExt; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Controller; + @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/user") @Tags({@Tag(name = "SDC Internal APIs")}) @@ -68,140 +67,105 @@ import java.util.List; public class UserAdminServlet extends BeGenericServlet { private static final String UTF_8 = "UTF-8"; - private static final String ROLE_DELIMITER = ","; + private static final String ROLE_DELIMITER = ","; private static final Logger log = Logger.getLogger(UserAdminServlet.class); private final UserBusinessLogic userBusinessLogic; private final UserBusinessLogicExt userBusinessLogicExt; - static class UserRole { - Role role; - - public Role getRole() { - return role; - } - - public void setRole(Role role) { - this.role = role; - } - - } - - UserAdminServlet(UserBusinessLogic userBusinessLogic, - ComponentsUtils componentsUtils, UserBusinessLogicExt userBusinessLogicExt) { + UserAdminServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, UserBusinessLogicExt userBusinessLogicExt) { super(userBusinessLogic, componentsUtils); this.userBusinessLogic = userBusinessLogic; this.userBusinessLogicExt = userBusinessLogicExt; } - ///////////////////////////////////////////////////////////////////////////////////////////////////// // retrieve all user details @GET @Path("/{userId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - - @Operation(description = "retrieve user details", method = "GET", - summary = "Returns user details according to userId",responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns user Ok"), - @ApiResponse(responseCode = "404", description = "User not found"), - @ApiResponse(responseCode = "405", description = "Method Not Allowed"), - @ApiResponse(responseCode = "500", description = "Internal Server Error") - }) + @Operation(description = "retrieve user details", method = "GET", summary = "Returns user details according to userId", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "404", description = "User not found"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public User get( - @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId, - @Context final HttpServletRequest request) { + public User get(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId, + @Context final HttpServletRequest request) { return userBusinessLogic.getUser(userId, false); } + ///////////////////////////////////////////////////////////////////////////////////////////////////// @GET @Path("/{userId}/role") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "retrieve user role", summary = "Returns user role according to userId", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), - @ApiResponse(responseCode = "200", description = "Returns user role Ok"), - @ApiResponse(responseCode = "404", description = "User not found"), - @ApiResponse(responseCode = "405", description = "Method Not Allowed"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), + @ApiResponse(responseCode = "200", description = "Returns user role Ok"), @ApiResponse(responseCode = "404", description = "User not found"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public String getRole( - @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId, - @Context final HttpServletRequest request) { + public String getRole(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId, + @Context final HttpServletRequest request) { User user = userBusinessLogic.getUser(userId, false); return "{ \"role\" : \"" + user.getRole() + "\" }"; } - ///////////////////////////////////////////////////////////////////////////////////////////////////// // update user role @POST @Path("/{userId}/role") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "update user role", summary = "Update user role", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Update user OK"), - @ApiResponse(responseCode = "400", description = "Invalid Content."), - @ApiResponse(responseCode = "403", description = "Missing information/Restricted operation"), - @ApiResponse(responseCode = "404", description = "User not found"), - @ApiResponse(responseCode = "405", description = "Method Not Allowed"), - @ApiResponse(responseCode = "409", description = "User already exists"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Update user OK"), @ApiResponse(responseCode = "400", description = "Invalid Content."), + @ApiResponse(responseCode = "403", description = "Missing information/Restricted operation"), + @ApiResponse(responseCode = "404", description = "User not found"), @ApiResponse(responseCode = "405", description = "Method Not Allowed"), + @ApiResponse(responseCode = "409", description = "User already exists"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public User updateUserRole( - @Parameter(description = "userId of user to get", - required = true) @PathParam("userId") final String userIdUpdateUser, - @Context final HttpServletRequest request, - @Parameter(description = "json describe the update role", required = true) UserRole newRole, - @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) { - + public User updateUserRole(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, + @Context final HttpServletRequest request, + @Parameter(description = "json describe the update role", required = true) UserRole newRole, + @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) { return userBusinessLogic.updateUserRole(modifierUserId, userIdUpdateUser, newRole.getRole().name()); } + ///////////////////////////////////////////////////////////////////////////////////////////////////// @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "add user", method = "POST", summary = "Provision new user", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "201", description = "New user created"), - @ApiResponse(responseCode = "400", description = "Invalid Content."), - @ApiResponse(responseCode = "403", description = "Missing information"), - @ApiResponse(responseCode = "405", description = "Method Not Allowed"), - @ApiResponse(responseCode = "409", description = "User already exists"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "201", description = "New user created"), @ApiResponse(responseCode = "400", description = "Invalid Content."), + @ApiResponse(responseCode = "403", description = "Missing information"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed"), + @ApiResponse(responseCode = "409", description = "User already exists"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) public Response createUser(@Context final HttpServletRequest request, - @Parameter(description = "json describe the user", required = true) User newUser, - @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) { - + @Parameter(description = "json describe the user", required = true) User newUser, + @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) { log.debug("modifier id is {}", modifierAttId); User user = userBusinessLogic.createUser(modifierAttId, newUser); - return Response.status(HttpStatus.CREATED_201) - .entity(user) - .build(); + return Response.status(HttpStatus.CREATED_201).entity(user).build(); } @GET @Path("/authorize") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "authorize", summary = "authorize user", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns user Ok"), - @ApiResponse(responseCode = "403", description = "Restricted Access"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "403", description = "Restricted Access"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public User authorize(@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) throws UnsupportedEncodingException { - + public User authorize(@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) + throws UnsupportedEncodingException { 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; - User authUser = new User(); authUser.setUserId(userId); authUser.setFirstName(firstName); @@ -214,12 +178,10 @@ public class UserAdminServlet extends BeGenericServlet { @Path("/admins") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "retrieve all administrators", method = "GET", summary = "Returns all administrators", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns user Ok"), - @ApiResponse(responseCode = "405", description = "Method Not Allowed"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @Operation(description = "retrieve all administrators", method = "GET", summary = "Returns all administrators", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "405", description = "Method Not Allowed"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public List getAdminsUser(@Context final HttpServletRequest request) { return userBusinessLogic.getAllAdminUsers(); @@ -229,24 +191,17 @@ public class UserAdminServlet extends BeGenericServlet { @Path("/users") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Retrieve the list of all active ASDC users or only group of users having specific roles.", - method = "GET", - summary = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Returns users Ok"), - @ApiResponse(responseCode = "204", description = "No provisioned ASDC users of requested role"), - @ApiResponse(responseCode = "403", description = "Restricted Access"), - @ApiResponse(responseCode = "400", description = "Missing content"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) - public List getUsersList(@Context final HttpServletRequest request, @Parameter( - description = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId, - @Parameter( - description = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) { - + @Operation(description = "Retrieve the list of all active ASDC users or only group of users having specific roles.", method = "GET", summary = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Returns users Ok"), + @ApiResponse(responseCode = "204", description = "No provisioned ASDC users of requested role"), + @ApiResponse(responseCode = "403", description = "Restricted Access"), @ApiResponse(responseCode = "400", description = "Missing content"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + public List getUsersList(@Context final HttpServletRequest request, + @Parameter(description = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId, + @Parameter(description = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) { 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); @@ -262,19 +217,28 @@ public class UserAdminServlet extends BeGenericServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "delete user", summary = "Delete user", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), - @ApiResponse(responseCode = "200", description = "Update deleted OK"), - @ApiResponse(responseCode = "400", description = "Invalid Content."), - @ApiResponse(responseCode = "403", description = "Missing information"), - @ApiResponse(responseCode = "404", description = "User not found"), - @ApiResponse(responseCode = "405", description = "Method Not Allowed"), - @ApiResponse(responseCode = "409", description = "Restricted operation"), - @ApiResponse(responseCode = "500", description = "Internal Server Error")}) + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))), + @ApiResponse(responseCode = "200", description = "Update deleted OK"), @ApiResponse(responseCode = "400", description = "Invalid Content."), + @ApiResponse(responseCode = "403", description = "Missing information"), @ApiResponse(responseCode = "404", description = "User not found"), + @ApiResponse(responseCode = "405", description = "Method Not Allowed"), + @ApiResponse(responseCode = "409", description = "Restricted operation"), + @ApiResponse(responseCode = "500", description = "Internal Server Error")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public User deActivateUser( - @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String modifierId) { + public User deActivateUser(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierId) { return userBusinessLogicExt.deActivateUser(modifierId, userId); } + + static class UserRole { + + Role role; + + public Role getRole() { + return role; + } + + public void setRole(Role role) { + this.role = role; + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/ComponentExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/ComponentExceptionMapper.java index 72b2362945..4b12b95f0c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/ComponentExceptionMapper.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/ComponentExceptionMapper.java @@ -23,6 +23,11 @@ package org.openecomp.sdc.be.servlets.exception; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.io.IOException; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; import org.onap.sdc.security.RepresentationUtils; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; @@ -31,12 +36,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Component; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; -import java.io.IOException; - @Component @Provider public class ComponentExceptionMapper implements ExceptionMapper { @@ -54,28 +53,22 @@ public class ComponentExceptionMapper implements ExceptionMapper { @Override public Response toResponse(Exception exception) { log.debug("#toResponse - An error occurred: ", exception); - return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500) - .entity(exception.getMessage()) - .build(); + 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/exception/PropertyConstraintExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/PropertyConstraintExceptionMapper.java index cc90ecf00a..320839a38e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/PropertyConstraintExceptionMapper.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/PropertyConstraintExceptionMapper.java @@ -17,25 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.servlets.exception; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import org.openecomp.sdc.common.log.wrappers.Logger; 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 PropertyConstraintExceptionMapper implements ExceptionMapper { +public class PropertyConstraintExceptionMapper implements ExceptionMapper { private static final Logger log = Logger.getLogger(PropertyConstraintExceptionMapper.class); private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); @@ -49,9 +46,6 @@ public class PropertyConstraintExceptionMapper implements ExceptionMapper { +public class StorageExceptionMapper implements ExceptionMapper { private static final Logger log = Logger.getLogger(DefaultExceptionMapper.class); private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); @@ -51,9 +48,6 @@ public class StorageExceptionMapper implements ExceptionMapper log.debug("#toResponse - An error occurred: ", exception); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(exception.getStorageOperationStatus()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, exception.getParams()); - return Response.status(responseFormat.getStatus()) - .entity(gson.toJson(responseFormat.getRequestError())) - .build(); + return Response.status(responseFormat.getStatus()).entity(gson.toJson(responseFormat.getRequestError())).build(); } - } 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 fec00d2f67..b5a4be421e 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.switchover.detector; import com.google.common.annotations.VisibleForTesting; @@ -39,41 +38,86 @@ import org.openecomp.sdc.common.http.client.api.HttpRequest; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; - @Component("switchover-detector") public class SwitchoverDetector { private static final String SWITCHOVER_DETECTOR_LOG_CONTEXT = "switchover.detector"; - + private static final Logger logger = Logger.getLogger(SwitchoverDetector.class); + ScheduledExecutorService switchoverDetectorScheduler = Executors + .newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "Switchover-Detector-Task")); + SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null; private SwitchoverDetectorConfig switchoverDetectorConfig; - private Properties authHeader = null; - private long detectorInterval = 60; - private int maxBeQueryAttempts = 3; - private int maxFeQueryAttempts = 3; - private Boolean beMatch = null; - private Boolean feMatch = null; + private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState(); + private ScheduledFuture scheduledFuture = null; - private static final Logger logger = Logger.getLogger(SwitchoverDetector.class); + public String getSiteMode() { + return siteMode; + } - private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState(); + public void setSiteMode(String mode) { + this.siteMode = mode; + } - private ScheduledFuture scheduledFuture = null; + @VisibleForTesting + void setSwitchoverDetectorConfig(SwitchoverDetectorConfig switchoverDetectorConfig) { + this.switchoverDetectorConfig = switchoverDetectorConfig; + } - ScheduledExecutorService switchoverDetectorScheduler = - Executors.newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "Switchover-Detector-Task")); + @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; + } + Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts(); + if (maxAttempts != null) { + maxBeQueryAttempts = maxAttempts; + } + maxAttempts = switchoverDetectorConfig.getFeResolveAttempts(); + if (maxAttempts != null) { + maxFeQueryAttempts = maxAttempts; + } + logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval); + this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask(); + startSwitchoverDetectorTask(); + logger.trace("Exit init method of SwitchoverDetector"); + } - SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null; + @PreDestroy + private void destroy() { + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + if (switchoverDetectorScheduler != null) { + switchoverDetectorScheduler.shutdown(); + } + } - public enum SwitchoverDetectorState { + /** + * This method starts the switchover detector threads in the background. + */ + public void startSwitchoverDetectorTask() { + if (this.scheduledFuture == null) { + this.scheduledFuture = this.switchoverDetectorScheduler + .scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS); + } + } + public enum SwitchoverDetectorState { UNKNOWN("unknown"), ACTIVE("active"), STANDBY("standby"); - private String state; SwitchoverDetectorState(String state) { @@ -86,9 +130,7 @@ public class SwitchoverDetector { } public enum SwitchoverDetectorGroup { - BE_SET("beSet"), FE_SET("feSet"); - private String group; SwitchoverDetectorGroup(String group) { @@ -100,26 +142,18 @@ public class SwitchoverDetector { } } - public String getSiteMode() { - return siteMode; - } - - public void setSiteMode(String mode) { - this.siteMode = mode; - } - public class SwitchoverDetectorScheduledTask implements Runnable { - private Boolean queryGss(String fqdn, String vip, int maxAttempts) { + ExecutorService switchoverDetectorExecutor = Executors + .newSingleThreadExecutor(runnable -> new Thread(runnable, "Switchover-Detector-Thread")); + private Boolean queryGss(String fqdn, String vip, int maxAttempts) { Boolean result = null; int attempts = 0; - 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) { @@ -129,28 +163,24 @@ public class SwitchoverDetector { } } if (null == result) { - BeEcompErrorManager.getInstance().logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, - "host " + fqdn + " not resolved after " + attempts + " attempts"); + BeEcompErrorManager.getInstance() + .logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, "host " + fqdn + " not resolved after " + attempts + " attempts"); } return result; } private Boolean queryBe() { - return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), - maxBeQueryAttempts); + return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), maxBeQueryAttempts); } private Boolean queryFe() { - return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), - maxFeQueryAttempts); + return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), maxFeQueryAttempts); } private void initializeSiteMode() { while (siteMode.equals(SwitchoverDetectorState.UNKNOWN.getState())) { - beMatch = queryBe(); feMatch = queryFe(); - if (beMatch != null && beMatch.equals(feMatch)) { if (beMatch) { setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); @@ -164,29 +194,20 @@ public class SwitchoverDetector { @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.equals(SwitchoverDetectorState.STANDBY.getState()) && (beRes || feRes) - && (!beMatch.equals(beRes) || !feMatch.equals(feRes)); + Boolean updateRequired = + siteMode.equals(SwitchoverDetectorState.STANDBY.getState()) && (beRes || feRes) && (!beMatch.equals(beRes) || !feMatch.equals(feRes)); Boolean prevModeStandby = siteMode.equals(SwitchoverDetectorState.STANDBY.getState()); - updateSiteModeAndPriority(beRes && feRes, prevModeStandby, updateRequired); - beMatch = beRes; feMatch = feRes; } - ExecutorService switchoverDetectorExecutor = - Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "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"); @@ -205,10 +226,8 @@ public class SwitchoverDetector { } 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) { @@ -218,11 +237,9 @@ public class SwitchoverDetector { } logger.debug("Error occurred during change site priority request, Result is {}", message, e); } - } private void publishNetwork() { - String url = switchoverDetectorConfig.getPublishNetworkUrl(); String body = switchoverDetectorConfig.getPublishNetworkBody(); try { @@ -235,70 +252,5 @@ public class SwitchoverDetector { logger.debug("Error occurred during publish network request, Result is {}", message, e); } } - - } - - @VisibleForTesting - void setSwitchoverDetectorConfig(SwitchoverDetectorConfig switchoverDetectorConfig) { - this.switchoverDetectorConfig = switchoverDetectorConfig; - } - - @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; - } - - Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts(); - if (maxAttempts != null) { - maxBeQueryAttempts = maxAttempts; - } - maxAttempts = switchoverDetectorConfig.getFeResolveAttempts(); - if (maxAttempts != null) { - maxFeQueryAttempts = maxAttempts; - } - - 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(); - } - } - - /** - * This method starts the switchover detector threads in the background. - */ - 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/togglz/CassandraCustomStateRepository.java b/catalog-be/src/main/java/org/openecomp/sdc/be/togglz/CassandraCustomStateRepository.java index 5e2f416159..f8f85fdd97 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/togglz/CassandraCustomStateRepository.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/togglz/CassandraCustomStateRepository.java @@ -17,10 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.togglz; import com.google.common.annotations.VisibleForTesting; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.cassandra.FeatureToggleDao; import org.openecomp.sdc.be.resources.data.togglz.FeatureToggleEvent; @@ -30,10 +32,6 @@ import org.togglz.core.Feature; import org.togglz.core.repository.FeatureState; import org.togglz.core.repository.StateRepository; -import javax.annotation.PostConstruct; -import java.util.List; -import java.util.stream.Collectors; - @Component public class CassandraCustomStateRepository implements StateRepository { @@ -52,15 +50,13 @@ public class CassandraCustomStateRepository implements StateRepository { @VisibleForTesting void removeUnusedItems() { List allEvents = featureToggleDao.getAllFeatures(); - - List eventsToDelete = allEvents.stream() - .filter(e-> ToggleableFeature.getFeatureByName(e.getFeatureName()) == null) - .collect(Collectors.toList()); + List eventsToDelete = allEvents.stream().filter(e -> ToggleableFeature.getFeatureByName(e.getFeatureName()) == null) + .collect(Collectors.toList()); if (!eventsToDelete.isEmpty()) { logger.debug("Found Feature toggles not in use [{}], they will be deleted", - eventsToDelete.stream().map(FeatureToggleEvent::getFeatureName).collect(Collectors.toList())); + eventsToDelete.stream().map(FeatureToggleEvent::getFeatureName).collect(Collectors.toList())); } - eventsToDelete.forEach(e->featureToggleDao.delete(e.getFeatureName())); + eventsToDelete.forEach(e -> featureToggleDao.delete(e.getFeatureName())); } @Override @@ -71,7 +67,6 @@ public class CassandraCustomStateRepository implements StateRepository { } FeatureState state = null; FeatureToggleEvent event = featureToggleDao.get(feature.name()); - if (event != null) { state = event.getFeatureState(); logger.debug("State of feature {} is {}", feature, state.getFeature()); @@ -87,5 +82,4 @@ public class CassandraCustomStateRepository implements StateRepository { CassandraOperationStatus status = featureToggleDao.save(new FeatureToggleEvent(featureState)); logger.debug("setFeatureState=> FeatureState {} is set with status {}", featureState.getFeature(), status); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/AttributeConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/AttributeConverter.java index a0f8d8b44f..83799e6405 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/AttributeConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/AttributeConverter.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; import com.google.gson.JsonElement; @@ -72,8 +71,8 @@ public class AttributeConverter { */ public ToscaAttribute convert(final AttributeDefinition attributeDefinition) throws ToscaConversionException { final ToscaAttribute toscaAttribute = new ToscaAttribute(); - LOGGER.trace("Converting attribute '{}' from type '{}' with default value '{}'", - attributeDefinition.getName(), attributeDefinition.getType(), attributeDefinition.getDefaultValue()); + LOGGER.trace("Converting attribute '{}' from type '{}' with default value '{}'", attributeDefinition.getName(), attributeDefinition.getType(), + attributeDefinition.getDefaultValue()); toscaAttribute.setEntrySchema(convert(attributeDefinition.getEntry_schema())); toscaAttribute.setType(attributeDefinition.getType()); toscaAttribute.setDescription(attributeDefinition.getDescription()); @@ -83,12 +82,11 @@ public class AttributeConverter { if (defaultValue != null) { toscaAttribute.setDefault(defaultValue); } - final Object value = convertToToscaObject(attributeDefinition.getName(), attributeDefinition.getType(), - attributeDefinition.getValue(), attributeDefinition.getEntry_schema(), false); + final Object value = convertToToscaObject(attributeDefinition.getName(), attributeDefinition.getType(), attributeDefinition.getValue(), + attributeDefinition.getEntry_schema(), false); if (value != null) { toscaAttribute.setValue(value); } - return toscaAttribute; } @@ -96,28 +94,24 @@ public class AttributeConverter { if (entrySchema == null) { return null; } - final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition(); toscaSchemaDefinition.setType(entrySchema.getType()); toscaSchemaDefinition.setDescription(entrySchema.getDescription()); return toscaSchemaDefinition; } - private Object convertToToscaObject(final String name, final String attributeType, String value, - final EntrySchema schemaDefinition, final boolean preserveEmptyValue) throws ToscaConversionException { + private Object convertToToscaObject(final String name, final String attributeType, String value, final EntrySchema schemaDefinition, + final boolean preserveEmptyValue) throws ToscaConversionException { final String innerType = schemaDefinition == null ? attributeType : schemaDefinition.getType(); - LOGGER.trace("Converting attribute '{}' of type '{}', value '{}', innerType '{}'", - name, attributeType, value, innerType); + LOGGER.trace("Converting attribute '{}' of type '{}', value '{}', innerType '{}'", name, attributeType, value, innerType); if (StringUtils.isEmpty(value)) { value = getTypeDefaultValue(attributeType); if (StringUtils.isEmpty(value)) { return null; } } - try { boolean isScalar = true; - ToscaPropertyType predefinedType = ToscaPropertyType.isValidType(attributeType); if (predefinedType == null) { //not predefined, search in existing data types @@ -133,7 +127,6 @@ public class AttributeConverter { if (isValueGetAttribute(valueAsJson)) { return ToscaMapValueConverter.getInstance().handleComplexJsonValue(valueAsJson.getAsJsonObject()); } - //if it has a converter if (predefinedType != null && predefinedType.getValueConverter() != null) { LOGGER.trace("It's well defined type. convert it"); @@ -143,23 +136,17 @@ public class AttributeConverter { if (isScalar) { return toscaMapValueConverter.handleComplexJsonValue(valueAsJson); } - //if it is a data type - return toscaMapValueConverter.convertDataTypeToToscaObject( - innerType, dataTypes, null, false, valueAsJson, preserveEmptyValue); - + return toscaMapValueConverter.convertDataTypeToToscaObject(innerType, dataTypes, null, false, valueAsJson, preserveEmptyValue); } catch (final JsonParseException e) { final String errorMsg = "Failed to parse json value"; - LOGGER.error(EcompLoggerErrorCode.SCHEMA_ERROR, "Attribute Converter", - errorMsg, e); + LOGGER.error(EcompLoggerErrorCode.SCHEMA_ERROR, "Attribute Converter", errorMsg, e); throw new ToscaConversionException(errorMsg, e); } catch (final Exception e) { final String errorMsg = "Unexpected error occurred while converting attribute value to TOSCA"; - LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "Attribute Converter", - errorMsg, e); + LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "Attribute Converter", errorMsg, e); throw new ToscaConversionException(errorMsg, e); } - } private JsonElement parseToJson(final String value) { @@ -180,5 +167,4 @@ public class AttributeConverter { private String getTypeDefaultValue(final String attributeType) { return DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(attributeType, dataTypes); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java index 74704caa64..ac4f8bf6c8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; @@ -70,7 +69,6 @@ import org.springframework.context.annotation.Scope; /** * Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template - * */ @org.springframework.stereotype.Component("capabilty-requirement-convertor") @Scope(value = "singleton") @@ -78,17 +76,17 @@ public class CapabilityRequirementConverter { private static final String NO_CAPABILITIES = "No Capabilities for node type"; private static final String NO_REQUIREMENTS = "No Requirements for node type"; - private static CapabilityRequirementConverter instance; private static final Logger logger = Logger.getLogger(CapabilityRequirementConverter.class); private static final String PATH_DELIMITER = "."; - private static final String FAILED_TO_FIND_CI_IN_PATH ="Failed to find ci in the path is {} component {}"; - + private static final String FAILED_TO_FIND_CI_IN_PATH = "Failed to find ci in the path is {} component {}"; + private static CapabilityRequirementConverter instance; @Autowired private ToscaOperationFacade toscaOperationFacade; @Autowired private PropertyConvertor propertyConvertor; - public CapabilityRequirementConverter() {} + public CapabilityRequirementConverter() { + } public static synchronized CapabilityRequirementConverter getInstance() { if (instance == null) { @@ -97,24 +95,22 @@ public class CapabilityRequirementConverter { return instance; } - public String buildCapabilityNameForComponentInstance( Map componentCache , ComponentInstance componentInstance, CapabilityDefinition c) { + public String buildCapabilityNameForComponentInstance(Map componentCache, ComponentInstance componentInstance, + CapabilityDefinition c) { String prefix = buildCapReqNamePrefix(componentInstance.getNormalizedName()); - if(ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())){ - return buildSubstitutedName(componentCache, c.getName(), c.getPreviousName(), c.getPath(), c.getOwnerId(), componentInstance) - .left() - .orValue(c.getName()); + if (ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) { + return buildSubstitutedName(componentCache, c.getName(), c.getPreviousName(), c.getPath(), c.getOwnerId(), componentInstance).left() + .orValue(c.getName()); } return c.getPreviousName(); } - public String buildRequirementNameForComponentInstance(Map componentCache, - ComponentInstance componentInstance, + public String buildRequirementNameForComponentInstance(Map componentCache, ComponentInstance componentInstance, RequirementDefinition r) { String prefix = buildCapReqNamePrefix(componentInstance.getNormalizedName()); if (ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) { - return buildSubstitutedName(componentCache, r.getName(), r.getPreviousName(), r.getPath(), r.getOwnerId(), - componentInstance).left() - .orValue(r.getName()); + return buildSubstitutedName(componentCache, r.getName(), r.getPreviousName(), r.getPath(), r.getOwnerId(), componentInstance).left() + .orValue(r.getName()); } return r.getPreviousName(); } @@ -125,23 +121,24 @@ public class CapabilityRequirementConverter { /** * 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 convertComponentInstanceCapabilities(ComponentInstance componentInstance, Map dataTypes, ToscaNodeTemplate nodeTemplate) { - + public Either convertComponentInstanceCapabilities(ComponentInstance componentInstance, + Map dataTypes, + ToscaNodeTemplate nodeTemplate) { Map> capabilitiesInst = componentInstance.getCapabilities(); - Map componentCache = new HashMap<>(); + Map componentCache = new HashMap<>(); if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) { Map capabilities = new HashMap<>(); - capabilitiesInst.entrySet().forEach( e -> { + capabilitiesInst.entrySet().forEach(e -> { List capList = e.getValue(); - if ( capList != null && !capList.isEmpty() ) { - capList.stream() - .forEach( c -> convertOverridenProperties( componentInstance, dataTypes, capabilities, c , - buildCapabilityNameForComponentInstance( componentCache , componentInstance , c ))); + if (capList != null && !capList.isEmpty()) { + capList.stream().forEach(c -> convertOverridenProperties(componentInstance, dataTypes, capabilities, c, + buildCapabilityNameForComponentInstance(componentCache, componentInstance, c))); } }); if (MapUtils.isNotEmpty(capabilities)) { @@ -151,21 +148,20 @@ public class CapabilityRequirementConverter { return Either.left(nodeTemplate); } - private void convertOverridenProperties(ComponentInstance componentInstance, Map dataTypes, Map capabilties, CapabilityDefinition c , String capabilityName) { + 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 -> convertOverriddenProperty(componentInstance, dataTypes, capabilties , p ,capabilityName)); + c.getProperties().stream().filter(p -> p.getValue() != null || p.getDefaultValue() != null) + .forEach(p -> convertOverriddenProperty(componentInstance, dataTypes, capabilties, p, capabilityName)); } } - private void convertOverriddenProperty(ComponentInstance componentInstance, Map dataTypes, Map capabilties, ComponentInstanceProperty p , String capabilityName) { + private void convertOverriddenProperty(ComponentInstance componentInstance, Map dataTypes, + Map capabilties, ComponentInstanceProperty p, String capabilityName) { if (logger.isDebugEnabled()) { logger.debug("Exist d property {} for capability {} with value {}", p.getName(), capabilityName, p.getValue()); } - ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent( capabilityName , key -> new ToscaTemplateCapability() ); - + ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent(capabilityName, key -> new ToscaTemplateCapability()); Map toscaCapProp = toscaTemplateCapability.getProperties(); if (toscaCapProp == null) { toscaCapProp = new HashMap<>(); @@ -175,38 +171,43 @@ public class CapabilityRequirementConverter { toscaTemplateCapability.setProperties(toscaCapProp); } - private Object convertInstanceProperty(Map dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) { + private Object convertInstanceProperty(Map dataTypes, ComponentInstance componentInstance, + ComponentInstanceProperty prop) { logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId()); String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue(); return propertyConvertor.convertToToscaObject(prop, propValue, dataTypes, false); } + /** * Allows to convert requirements of a node type to tosca template requirements representation + * * @param component * @param nodeType * @return */ - public Either convertRequirements(Map componentsCache, Component component, ToscaNodeType nodeType) { + public Either convertRequirements(Map componentsCache, Component component, + ToscaNodeType nodeType) { List> toscaRequirements = convertRequirementsAsList(componentsCache, 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) { + public Either convertSubstitutionMappingRequirements(Map componentsCache, Component component, + SubstitutionMapping substitutionMappings) { Either result = Either.left(substitutionMappings); Either, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component); - if(toscaRequirementsRes.isRight()){ + if (toscaRequirementsRes.isRight()) { result = Either.right(toscaRequirementsRes.right().value()); logger.debug("Failed convert requirements for the component {}. ", component.getName()); } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { @@ -219,19 +220,17 @@ public class CapabilityRequirementConverter { /** * Allows to convert requirements of a server proxy node type to tosca template requirements + * * @param instanceProxy * @return converted tosca template requirements */ - List> convertProxyRequirements(Map componentCache, - ComponentInstance instanceProxy) { + List> convertProxyRequirements(Map componentCache, ComponentInstance instanceProxy) { Map> requirements = instanceProxy.getRequirements(); List> toscaRequirements = new ArrayList<>(); if (requirements != null) { - requirements.entrySet().stream() - .flatMap(e -> e.getValue().stream()) - .forEach(req -> { + requirements.entrySet().stream().flatMap(e -> e.getValue().stream()).forEach(req -> { ImmutablePair pair = convertProxyRequirement( - buildRequirementNameForComponentInstance(componentCache, instanceProxy, req), req); + buildRequirementNameForComponentInstance(componentCache, instanceProxy, req), req); Map requirement = new HashMap<>(); requirement.put(pair.left, pair.right); toscaRequirements.add(requirement); @@ -239,12 +238,10 @@ public class CapabilityRequirementConverter { } else { logger.debug(NO_REQUIREMENTS); } - return toscaRequirements; } - private ImmutablePair convertProxyRequirement(String requirementName, - RequirementDefinition r) { + private ImmutablePair convertProxyRequirement(String requirementName, RequirementDefinition r) { ToscaRequirement toscaRequirement = createToscaRequirement(r); return new ImmutablePair<>(requirementName, toscaRequirement); } @@ -255,9 +252,9 @@ public class CapabilityRequirementConverter { if (requirements != null) { for (Map.Entry> entry : requirements.entrySet()) { entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> { - ImmutablePair pair = convertRequirement(componentsCache, component, ModelConverter.isAtomicComponent(component), r); + ImmutablePair pair = convertRequirement(componentsCache, component, + ModelConverter.isAtomicComponent(component), r); Map requirement = new HashMap<>(); - requirement.put(pair.left, pair.right); toscaRequirements.add(requirement); }); @@ -270,21 +267,23 @@ public class CapabilityRequirementConverter { } private boolean filter(Component component, String ownerId) { - return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null); + 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 dropLast( String path, String delimiter ) { - if (isBlank(path) || isBlank(delimiter)){ + 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) { + private Either, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map componentsCache, + Component component) { Map> requirements = component.getRequirements(); Either, ToscaError> result; if (requirements != null) { @@ -296,53 +295,54 @@ public class CapabilityRequirementConverter { return result; } - private Either, ToscaError> buildAddSubstitutionMappingsRequirements(Map componentsCache, Component component, Map> requirements) { - + 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(RequirementDefinition::isExternal) - .filter(r->!addEntry(componentsCache, toscaRequirements, component, new SubstitutionEntry(r.getName(), r.getParentName(), ""), r.getPreviousName(), r.getOwnerId(), r.getPath())) - .findAny(); - if(failedToAddRequirement.isPresent()){ + Optional failedToAddRequirement = entry.getValue().stream().filter(RequirementDefinition::isExternal).filter( + r -> !addEntry(componentsCache, toscaRequirements, component, new SubstitutionEntry(r.getName(), r.getParentName(), ""), + r.getPreviousName(), r.getOwnerId(), r.getPath())).findAny(); + if (failedToAddRequirement.isPresent()) { logger.debug("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ", - failedToAddRequirement.get().getName(), component.getName()); + 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){ + if (result == null) { result = Either.left(toscaRequirements); } return result; } - private Either, ToscaError> buildAddSubstitutionMappingsCapabilities(Map componentsCache, Component component, Map> capabilities) { - + private Either, ToscaError> buildAddSubstitutionMappingsCapabilities(Map componentsCache, + Component component, + Map> capabilities) { Map toscaCapabilities = new HashMap<>(); Either, ToscaError> result = null; for (Map.Entry> entry : capabilities.entrySet()) { - Optional failedToAddRequirement = entry.getValue() - .stream() - .filter(c->!addEntry(componentsCache, toscaCapabilities, component, new SubstitutionEntry(c.getName(), c.getParentName(), ""), c.getPreviousName(), c.getOwnerId(), c.getPath())) - .findAny(); - if(failedToAddRequirement.isPresent()){ + Optional failedToAddRequirement = entry.getValue().stream().filter( + c -> !addEntry(componentsCache, toscaCapabilities, component, new SubstitutionEntry(c.getName(), c.getParentName(), ""), + c.getPreviousName(), c.getOwnerId(), c.getPath())).findAny(); + if (failedToAddRequirement.isPresent()) { logger.debug("Failed to convert capability {} for substitution mappings section of a tosca template of the component {}. ", - failedToAddRequirement.get().getName(), component.getName()); + failedToAddRequirement.get().getName(), component.getName()); result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR); } logger.debug("Finish convert capabilities for the component {}. ", component.getName()); } - if(result == null){ + if (result == null) { result = Either.left(toscaCapabilities); } return result; } - private boolean addEntry(Map componentsCache, Map capReqMap, Component component, SubstitutionEntry entry, String previousName, String ownerId, List path){ - - if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, entry.getFullName(), previousName, path, ownerId, entry)){ + private boolean addEntry(Map componentsCache, Map capReqMap, Component component, SubstitutionEntry entry, + String previousName, String ownerId, List path) { + if (shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, entry.getFullName(), + previousName, path, ownerId, entry)) { return false; } logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId()); @@ -351,22 +351,22 @@ public class CapabilityRequirementConverter { } 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.isNotComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext(); } - private boolean buildSubstitutedNamePerInstance(Map componentsCache, Component component, String name, String previousName, List path, String ownerId, SubstitutionEntry entry) { + private boolean buildSubstitutedNamePerInstance(Map componentsCache, Component component, String name, String previousName, + List path, String ownerId, SubstitutionEntry entry) { String fullName; String sourceName; String prefix; - if(CollectionUtils.isNotEmpty(component.getGroups())) { + if (CollectionUtils.isNotEmpty(component.getGroups())) { Optional groupOpt = component.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst(); if (groupOpt.isPresent()) { prefix = buildCapReqNamePrefix(groupOpt.get().getNormalizedName()); - if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){ + if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) { sourceName = name; fullName = prefix + sourceName; } else { @@ -379,22 +379,19 @@ public class CapabilityRequirementConverter { return true; } } - - Optional ci = - component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); - if(!ci.isPresent()){ + Optional ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path))) + .findFirst(); + if (!ci.isPresent()) { logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId()); - Collections.reverse(path); - logger.debug("try to reverse path {} component {}", path, component.getUniqueId()); - ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); + ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); } - if(ci.isPresent()){ + if (ci.isPresent()) { prefix = buildCapReqNamePrefix(ci.get().getNormalizedName()); - if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){ + if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) { Either buildSubstitutedName = buildSubstitutedName(componentsCache, name, previousName, path, ownerId, ci.get()); - if(buildSubstitutedName.isRight()){ + if (buildSubstitutedName.isRight()) { logger.debug("Failed buildSubstitutedName name {} path {} component {}", name, path, component.getUniqueId()); return false; } @@ -414,23 +411,27 @@ public class CapabilityRequirementConverter { } private void addEntry(Map toscaRequirements, Component component, List capPath, SubstitutionEntry entry) { - Optional findFirst = component.safeGetComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst(); + Optional findFirst = component.safeGetComponentInstances().stream() + .filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst(); findFirst.ifPresent(componentInstance -> entry.setOwner(componentInstance.getName())); if (StringUtils.isNotEmpty(entry.getOwner()) && StringUtils.isNotEmpty(entry.getSourceName())) { - toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() }); + toscaRequirements.put(entry.getFullName(), new String[]{entry.getOwner(), entry.getSourceName()}); } } - public Either buildSubstitutedName(Map componentsCache, String name, String previousName, List path, String ownerId, ComponentInstance instance) { - if(StringUtils.isNotEmpty(previousName)){ + public Either buildSubstitutedName(Map componentsCache, String name, String previousName, List path, + String ownerId, ComponentInstance instance) { + if (StringUtils.isNotEmpty(previousName)) { return Either.left(name); } 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()); + 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()); return Either.right(false); } - List reducedPath = ownerId !=null ? getReducedPathByOwner(path , ownerId ) : getReducedPath(path) ; + List reducedPath = ownerId != null ? getReducedPathByOwner(path, ownerId) : getReducedPath(path); logger.debug("reducedPath for ownerId {}, reducedPath {} ", ownerId, reducedPath); reducedPath.remove(reducedPath.size() - 1); return buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name, previousName); @@ -440,7 +441,8 @@ public class CapabilityRequirementConverter { return buildCapReqNamePerOwnerByPath(componentsCache, component, r.getName(), r.getPreviousName(), r.getPath()); } - private ImmutablePair convertRequirement(Map componentsCache, Component component, boolean isNodeType, RequirementDefinition r) { + private ImmutablePair convertRequirement(Map componentsCache, Component component, + boolean isNodeType, RequirementDefinition r) { String name = r.getName(); if (!isNodeType && ToscaUtils.isNotComplexVfc(component)) { name = buildReqNamePerOwnerByPath(componentsCache, component, r); @@ -452,7 +454,6 @@ public class CapabilityRequirementConverter { private ToscaRequirement createToscaRequirement(RequirementDefinition r) { ToscaRequirement toscaRequirement = new ToscaRequirement(); - List occurrences = new ArrayList<>(); occurrences.add(Integer.valueOf(r.getMinOccurrences())); if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { @@ -469,57 +470,58 @@ public class CapabilityRequirementConverter { /** * Allows to convert capabilities of a node type to tosca template capabilities + * * @param component * @param dataTypes * @return */ - public Map convertCapabilities(Map componentsCache, Component component, Map dataTypes) { + public Map convertCapabilities(Map componentsCache, 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 -> convertCapability(componentsCache, component, toscaCapabilities, isNodeType, c, dataTypes , c.getName())); + entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())) + .forEach(c -> convertCapability(componentsCache, 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 instanceProxy * @param dataTypes * @return */ - public Map convertProxyCapabilities(Map componentCache, - ComponentInstance instanceProxy, + public Map convertProxyCapabilities(Map componentCache, ComponentInstance instanceProxy, Map dataTypes) { Map> capabilities = instanceProxy.getCapabilities(); Map toscaCapabilities = new HashMap<>(); if (capabilities != null) { for (Map.Entry> entry : capabilities.entrySet()) { - entry.getValue() - .stream() - .forEach(c -> convertProxyCapability(toscaCapabilities, c, dataTypes , - buildCapabilityNameForComponentInstance( componentCache , instanceProxy , c ))); + entry.getValue().stream().forEach(c -> convertProxyCapability(toscaCapabilities, 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) { + public Either, ToscaError> convertSubstitutionMappingCapabilities(Map componentsCache, + Component component) { Map> capabilities = component.getCapabilities(); Either, ToscaError> res; if (capabilities != null) { @@ -540,7 +542,8 @@ public class CapabilityRequirementConverter { createToscaCapability(toscaCapabilities, c, dataTypes, capabilityName); } - private void convertCapability(Map componentsCache, Component component, Map toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map dataTypes , String capabilityName) { + private void convertCapability(Map componentsCache, Component component, Map toscaCapabilities, + boolean isNodeType, CapabilityDefinition c, Map dataTypes, String capabilityName) { String name = isNoneBlank(capabilityName) ? capabilityName : c.getName(); if (!isNodeType && ToscaUtils.isNotComplexVfc(component)) { name = buildCapNamePerOwnerByPath(componentsCache, c, component); @@ -554,7 +557,6 @@ public class CapabilityRequirementConverter { ToscaCapability toscaCapability = new ToscaCapability(); toscaCapability.setDescription(c.getDescription()); toscaCapability.setType(c.getType()); - List occurrences = new ArrayList<>(); occurrences.add(Integer.valueOf(c.getMinOccurrences())); if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { @@ -563,7 +565,6 @@ public class CapabilityRequirementConverter { occurrences.add(Integer.valueOf(c.getMaxOccurrences())); } toscaCapability.setOccurrences(occurrences); - toscaCapability.setValid_source_types(c.getValidSourceTypes()); List properties = c.getProperties(); if (isNotEmpty(properties)) { @@ -577,36 +578,36 @@ public class CapabilityRequirementConverter { toscaCapabilities.put(name, toscaCapability); } - private String buildCapReqNamePerOwnerByPath(Map componentsCache, Component component, String name, String previousName, List path) { + private String buildCapReqNamePerOwnerByPath(Map componentsCache, Component component, String name, String previousName, + List path) { if (CollectionUtils.isEmpty(path)) { return name; } String ownerId = path.get(path.size() - 1); String prefix; - if(CollectionUtils.isNotEmpty(component.getGroups())) { + if (CollectionUtils.isNotEmpty(component.getGroups())) { Optional groupOpt = component.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst(); if (groupOpt.isPresent()) { prefix = buildCapReqNamePrefix(groupOpt.get().getNormalizedName()); - if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){ + if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) { return prefix + name; } return name; } } - Optional ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); - if(!ci.isPresent()){ + Optional ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path))) + .findFirst(); + if (!ci.isPresent()) { logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId()); - Collections.reverse(path); - logger.debug("try to reverse path {} component {}", path, component.getUniqueId()); - ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); + ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); } - if(ci.isPresent()){ + if (ci.isPresent()) { prefix = buildCapReqNamePrefix(ci.get().getNormalizedName()); - if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){ + if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) { Either buildSubstitutedName = buildSubstitutedName(componentsCache, name, previousName, path, ownerId, ci.get()); - if(buildSubstitutedName.isRight()){ + if (buildSubstitutedName.isRight()) { logger.debug("Failed buildSubstitutedName name {} path {} component {}", name, path, component.getUniqueId()); } return prefix + buildSubstitutedName.left().value(); @@ -615,8 +616,10 @@ public class CapabilityRequirementConverter { } return StringUtils.EMPTY; } + /** * Allows to build substituted name of capability\requirement of the origin component instance according to the path + * * @param componentsCache * @param originComponent * @param path @@ -624,13 +627,14 @@ public class CapabilityRequirementConverter { * @param previousName * @return */ - public Either buildSubstitutedName(Map componentsCache, Component originComponent, List path, String name, String previousName) { - if(StringUtils.isNotEmpty(previousName)){ + public Either buildSubstitutedName(Map componentsCache, Component originComponent, List path, + String name, String previousName) { + if (StringUtils.isNotEmpty(previousName)) { return Either.left(name); } StringBuilder substitutedName = new StringBuilder(); boolean nameBuiltSuccessfully = true; - if(isNotEmpty(path) && ToscaUtils.isNotComplexVfc(originComponent)){ + if (isNotEmpty(path) && ToscaUtils.isNotComplexVfc(originComponent)) { List reducedPath = getReducedPath(path); Collections.reverse(reducedPath); nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName); @@ -638,46 +642,51 @@ public class CapabilityRequirementConverter { return nameBuiltSuccessfully ? Either.left(substitutedName.append(name).toString()) : Either.right(nameBuiltSuccessfully); } - protected List getReducedPathByOwner(List path , String ownerId) { + protected List getReducedPathByOwner(List path, String ownerId) { logger.debug("ownerId {}, path {} ", ownerId, path); - if ( CollectionUtils.isEmpty(path) ){ + if (CollectionUtils.isEmpty(path)) { logger.debug("cannot perform reduce by owner, path to component is empty"); return path; } - if ( isBlank(ownerId) ){ + 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 )); + 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()); + 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.isNotComplexVfc(originComponent)){ + private boolean appendNameRecursively(Map componentsCache, Component originComponent, Iterator instanceIdIter, + StringBuilder substitutedName) { + if (isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && ToscaUtils.isNotComplexVfc(originComponent)) { String ownerId = instanceIdIter.next(); - Optional instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(ownerId)).findFirst(); - if(instanceOpt.isPresent()){ + Optional instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(ownerId)) + .findFirst(); + if (instanceOpt.isPresent()) { substitutedName.append(instanceOpt.get().getNormalizedName()).append(PATH_DELIMITER); Either getOriginRes = getOriginComponent(componentsCache, instanceOpt.get()); - if(getOriginRes.isRight()){ + if (getOriginRes.isRight()) { return false; } appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName); - } else if(CollectionUtils.isNotEmpty(originComponent.getGroups())){ + } else if (CollectionUtils.isNotEmpty(originComponent.getGroups())) { Optional groupOpt = originComponent.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst(); - if(!groupOpt.isPresent()){ - logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId()); + if (!groupOpt.isPresent()) { + logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, + originComponent.getUniqueId()); return false; } substitutedName.append(groupOpt.get().getNormalizedName()).append(PATH_DELIMITER); } else { - logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId()); + logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, + originComponent.getUniqueId()); return false; } } @@ -687,12 +696,12 @@ public class CapabilityRequirementConverter { Either getOriginComponent(Map componentsCache, ComponentInstance instance) { Either result; Either getOriginRes; - if(componentsCache.containsKey(instance.getActualComponentUid())){ + 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()){ + if (getOriginRes.isRight()) { logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid()); result = Either.right(false); } else { @@ -706,15 +715,14 @@ public class CapabilityRequirementConverter { private ComponentParametersView getFilter(ComponentInstance instance) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreComponentInstances(false); - if(instance.getIsProxy()){ + if (instance.getIsProxy()) { filter.setIgnoreCapabilities(false); filter.setIgnoreRequirements(false); filter.setIgnoreCategories(false); } - if(instance.getOriginType() == OriginTypeEnum.VF){ + if (instance.getOriginType() == OriginTypeEnum.VF) { filter.setIgnoreGroups(false); } return filter; } - -} \ No newline at end of file +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ComponentCache.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ComponentCache.java index 7871176dab..57ebcf6822 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ComponentCache.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ComponentCache.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; import static org.openecomp.sdc.be.utils.CommonBeUtils.compareAsdcComponentVersions; @@ -35,11 +34,11 @@ import org.openecomp.sdc.be.model.Component; * Provides caching abilities for components */ public final class ComponentCache { - // TODO: Make this final whenever possible. The current code using the class + + private final BinaryOperator merge; // does not allow this. private Map entries = HashMap.empty(); - private final BinaryOperator merge; private ComponentCache(BinaryOperator merge) { this.merge = merge; @@ -47,6 +46,7 @@ public final class ComponentCache { /** * Creates an overwritable cache based on a merging strategy + * * @param merge The strategy used to merge two values which keys are the same */ public static ComponentCache overwritable(BinaryOperator merge) { @@ -55,8 +55,9 @@ public final class ComponentCache { /** * Creates a cached entry - * @param id The id of the entry - * @param fileName the filename of the entry + * + * @param id The id of the entry + * @param fileName the filename of the entry * @param component the cached component */ public static CacheEntry entry(String id, String fileName, Component component) { @@ -65,57 +66,22 @@ public final class ComponentCache { /** * Decorate the cache with a listener called whenever a value is merged + * * @param bc the consumer called when a value is merged */ public ComponentCache onMerge(BiConsumer bc) { return new ComponentCache((oldValue, newValue) -> { CacheEntry value = merge.apply(oldValue, newValue); - if(value.equals(newValue)) { + if (value.equals(newValue)) { bc.accept(oldValue, newValue); } return value; }); } - public interface MergeStrategy { - - /** - * A strategy designed to favour the latest component version when merging two cached entries - */ - static BinaryOperator overwriteIfSameVersions() { - return (oldValue, newValue) -> - compareAsdcComponentVersions(newValue.getComponentVersion(), oldValue.getComponentVersion()) ? - newValue : oldValue; - } - } - - /** - * Entry stored by the cache - */ - @EqualsAndHashCode - public static final class CacheEntry { - final String id; - - final String fileName; - - final Component component; - CacheEntry(String id, String fileName, Component component) { - this.id = id; - this.fileName = fileName; - this.component = component; - } - - public String getComponentVersion() { - return component.getVersion(); - } - } - - // TODO: Encapsulate the cache and expose functions to interact with it // For now we'll keep this as is, to prevent the refactoring to be too big public Iterable> iterable() { - return all().map(e -> - new ImmutableTriple<>(e.id, e.fileName, e.component) - ); + return all().map(e -> new ImmutableTriple<>(e.id, e.fileName, e.component)); } /** @@ -124,9 +90,11 @@ public final class ComponentCache { public Stream all() { return entries.values().toStream(); } + // TODO: Encapsulate the cache and expose functions to interact with it /** * Tells if an entry has been cached for a specific key + * * @param key The key used to index the entry */ public boolean notCached(String key) { @@ -134,23 +102,50 @@ public final class ComponentCache { } /** - * Store an entry in the cache. Keep in mind that currently this mutates the cache and does not work in a - * referentially transparent way (This should be fixed whenever possible). + * Store an entry in the cache. Keep in mind that currently this mutates the cache and does not work in a referentially transparent way (This + * should be fixed whenever possible). * - * @param id The id of the entry - * @param fileName the filename of the entry + * @param id The id of the entry + * @param fileName the filename of the entry * @param component the cached component */ - public ComponentCache put( - String id, - String fileName, - Component component - ) { + public ComponentCache put(String id, String fileName, Component component) { String uuid = component.getInvariantUUID(); CacheEntry entry = new CacheEntry(id, fileName, component); // TODO: Make the entries final whenever possible. The current code using the class does not allow this entries = entries.put(uuid, entry, merge); - return this; } + + public interface MergeStrategy { + + /** + * A strategy designed to favour the latest component version when merging two cached entries + */ + static BinaryOperator overwriteIfSameVersions() { + return (oldValue, newValue) -> compareAsdcComponentVersions(newValue.getComponentVersion(), oldValue.getComponentVersion()) ? newValue + : oldValue; + } + } + + /** + * Entry stored by the cache + */ + @EqualsAndHashCode + public static final class CacheEntry { + + final String id; + final String fileName; + final Component component; + + CacheEntry(String id, String fileName, Component component) { + this.id = id; + this.fileName = fileName; + this.component = component; + } + + public String getComponentVersion() { + return component.getVersion(); + } + } } 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 fe802f9534..3597c5c23c 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 @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; - import static org.openecomp.sdc.be.tosca.ComponentCache.MergeStrategy.overwriteIfSameVersions; import static org.openecomp.sdc.be.tosca.FJToVavrHelper.Try0.fromEither; import fj.F; import fj.data.Either; -import java.text.SimpleDateFormat; import io.vavr.Tuple2; import io.vavr.control.Option; import io.vavr.control.Try; @@ -34,6 +31,7 @@ import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; +import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -114,76 +112,67 @@ import org.yaml.snakeyaml.Yaml; /** * @author tg851x - * */ @org.springframework.stereotype.Component("csar-utils") public class CsarUtils { + + public static final String NODES_YML = "nodes.yml"; + public static final String ARTIFACTS_PATH = "Artifacts/"; + public static final String WORKFLOW_ARTIFACT_DIR = "Workflows" + File.separator + "BPMN" + File.separator; + public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment" + File.separator; + public static final String ARTIFACTS = "Artifacts"; + public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; private static final Logger log = Logger.getLogger(CsarUtils.class); private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(CsarUtils.class.getName()); private static final String PATH_DELIMITER = "/"; - public static final String NODES_YML = "nodes.yml"; - @Autowired - private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; - @Autowired - private ArtifactCassandraDao artifactCassandraDao; - @Autowired - private ComponentsUtils componentsUtils; - @Autowired - private ToscaExportHandler toscaExportUtils; - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - @Autowired(required = false) - private List generators; - private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); private static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); - public static final String ARTIFACTS_PATH = "Artifacts/"; private static final String RESOURCES_PATH = "Resources/"; private static final String DEFINITIONS_PATH = "Definitions/"; - public static final String WORKFLOW_ARTIFACT_DIR = "Workflows"+File.separator+"BPMN"+File.separator; - public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment"+File.separator; 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"; // add manifest - private static final String Service_Manifest = "NS.mf"; - public static final String ARTIFACTS = "Artifacts"; + private static final String Service_Manifest = "NS.mf"; private static final String DEFINITION = "Definitions"; private static final String DEL_PATTERN = "([/\\\\]+)"; private static final String WORD_PATTERN = "\\w\\_\\@\\-\\.\\s]+)"; public static final String VALID_ENGLISH_ARTIFACT_NAME = "([" + WORD_PATTERN; + public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + + // Artifact Group (i.e Deployment/Informational) + VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN + + // Artifact Type + VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN + + // Artifact Any File Name + ".+"; + public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN + + // Service Template File Name + VALID_ENGLISH_ARTIFACT_NAME; private static final String VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS = "([\\d" + WORD_PATTERN; private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}"; - - private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + - ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + - VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + - VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + - VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + - VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS; - - public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+ - // Artifact Group (i.e Deployment/Informational) - VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN + - // Artifact Type - VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN + - // Artifact Any File Name - ".+"; - - public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+ - // Service Template File Name - VALID_ENGLISH_ARTIFACT_NAME; - - public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; + private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = + ARTIFACTS + DEL_PATTERN + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS; private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; - + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + @Autowired + private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; + @Autowired + private ArtifactCassandraDao artifactCassandraDao; + @Autowired + private ComponentsUtils componentsUtils; + @Autowired + private ToscaExportHandler toscaExportUtils; + @Autowired(required = false) + private List generators; private String versionFirstThreeOctets; public CsarUtils() { - if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ + if (SDC_VERSION != null && !SDC_VERSION.isEmpty()) { Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); matcher.find(); setVersionFirstThreeOctets(matcher.group(0)); @@ -192,39 +181,201 @@ public class CsarUtils { } } + private static F> iff(Predicate p, Function> ifTrue) { + return l -> p.test(l) ? ifTrue.apply(l) : Either.left(l); + } + + private static F iff(Predicate p, Supplier s, Function orElse) { + return a -> p.test(a) ? s.get() : orElse.apply(a); + } + + /** + * 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 -> extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip -> addExtractedVfcArtifact(ip, 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) { + String vfcToscaNamespace = extractedVfcArtifact.getKey(); + artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>()); + artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue()); + } + + private static Optional> extractVfcArtifact(Entry entry, + Map>> collectedWarningMessages) { + String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER); + String groupType = parsedCsarArtifactPath[2].toUpperCase(); + return detectArtifactGroupType(groupType, collectedWarningMessages).left() + .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath)) + .either(ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)), b -> Optional.empty()); + } + + 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 F buildArtifactDefinitionFromCsarArtifactPath(Entry entry, + Map>> collectedWarningMessages, + String[] parsedCsarArtifactPath) { + return 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; + }; + } + /** + * 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) { + try { + String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER); + String groupType = parsedArtifactPath[1]; + String receivedTypeName = parsedArtifactPath[2]; + String artifactFileNameType = parsedArtifactPath[3]; + return detectArtifactGroupType(groupType, collectedWarningMessages).left().bind(artifactGroupType -> { + String artifactType = detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages); + return Either + .left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, artifactType, artifactGroupType, payloadData, null, true)); + }); + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + return Either.right(false); + } + } + + 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(final ArtifactGroupTypeEnum artifactGroupType, final String receivedTypeName, + final String warningMessage, final Map>> collectedWarningMessages, + final String... arguments) { + final ArtifactConfiguration artifactConfiguration = ArtifactConfigManager.getInstance() + .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE).orElse(null); + if (artifactConfiguration == null) { + final List messageArguments = new ArrayList<>(); + messageArguments.add(receivedTypeName); + messageArguments.addAll(Arrays.asList(arguments)); + if (!collectedWarningMessages.containsKey(warningMessage)) { + final Set> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + } + return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName; + } + + /** * @param component * @param getFromCS * @param isInCertificationRequest * @return */ public Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { - loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED,"Starting to create Csar for component {} ",component.getName()); + loggerSupportability + .log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED, "Starting to create Csar for component {} ", component.getName()); 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(); - - return generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest) - .left().map(responseFormat -> { - loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE, - "Ended create Csar for component {} ", component.getName()); + return generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest).left().map(responseFormat -> { + loggerSupportability + .log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE, "Ended create Csar for component {} ", component.getName()); return responseFormat; }); } - private Either generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest) { - try (ByteArrayOutputStream out = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(out)) { + private Either generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, + boolean isInCertificationRequest) { + 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)); @@ -234,160 +385,118 @@ public class CsarUtils { log.debug("Failed to populate CSAR zip file {}. Please fix DB table accordingly ", 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 {}. Please fix DB table accordingly ", 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) throws IOException { - - ArtifactDefinition artifactDef = component - .getToscaArtifacts() - .get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - - Either toscaRepresentation = - fetchToscaRepresentation(component, getFromCS, artifactDef); + } + private Either populateZip(Component component, boolean getFromCS, ZipOutputStream zip, + boolean isInCertificationRequest) throws IOException { + ArtifactDefinition artifactDef = component.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + Either toscaRepresentation = fetchToscaRepresentation(component, getFromCS, artifactDef); // This should not be done but in order to keep the refactoring small enough we stop here. + // TODO: Refactor the rest of this function byte[] mainYaml; List> dependencies; - if(toscaRepresentation.isLeft()) { + if (toscaRepresentation.isLeft()) { mainYaml = toscaRepresentation.left().value().getMainYaml(); dependencies = toscaRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>()); } else { return Either.right(toscaRepresentation.right().value()); } - String fileName = artifactDef.getArtifactName(); zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); zip.write(mainYaml); - LifecycleStateEnum lifecycleState = component.getLifecycleState(); addServiceMf(component, zip, lifecycleState, isInCertificationRequest, fileName, mainYaml); - //US798487 - Abstraction of complex types - if (!ModelConverter.isAtomicComponent(component)){ + if (!ModelConverter.isAtomicComponent(component)) { log.debug("Component {} is complex - generating abstract type for it..", component.getName()); - writeComponentInterface(component, zip, fileName, false); + writeComponentInterface(component, zip, fileName, false); } - //UID Either zipOutputStreamOrResponseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies); if (zipOutputStreamOrResponseFormat != null && zipOutputStreamOrResponseFormat.isRight()) { - return zipOutputStreamOrResponseFormat; + return zipOutputStreamOrResponseFormat; } - //retrieve SDC.zip from Cassandra Either latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); - - if(latestSchemaFilesFromCassandra.isRight()){ + if (latestSchemaFilesFromCassandra.isRight()) { log.error("Error retrieving SDC Schema files from cassandra"); return Either.right(latestSchemaFilesFromCassandra.right().value()); } - final byte[] schemaFileZip = latestSchemaFilesFromCassandra.left().value(); - final List nodesFromPackage = findNonRootNodesFromPackage(dependencies); - //add files from retrieved SDC.zip to Definitions folder in CSAR addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage); - Either collectedComponentCsarDefinition = collectComponentCsarDefinition(component); - if (collectedComponentCsarDefinition.isRight()) { return Either.right(collectedComponentCsarDefinition.right().value()); } - if (generators != null) { - for (CsarEntryGenerator generator: generators) { - log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName()); - for (Entry pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) { + for (CsarEntryGenerator generator : generators) { + log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName()); + for (Entry pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) { zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey())); zip.write(pluginGeneratedFile.getValue()); - } - } + } + } } - return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); } - private void addServiceMf(Component component, ZipOutputStream zip, LifecycleStateEnum lifecycleState, boolean isInCertificationRequest, String fileName, byte[] mainYaml) throws IOException{ + private void addServiceMf(Component component, ZipOutputStream zip, LifecycleStateEnum lifecycleState, boolean isInCertificationRequest, + String fileName, byte[] mainYaml) throws IOException { // add mf - if((component.getComponentType() == ComponentTypeEnum.SERVICE) && (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)){ + if ((component.getComponentType() == ComponentTypeEnum.SERVICE) && (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { String serviceName = component.getName(); String createdBy = component.getCreatorUserId(); String serviceVersion; - if(isInCertificationRequest){ + if (isInCertificationRequest) { int tmp = Integer.valueOf(component.getVersion().split("\\.")[0]) + 1; serviceVersion = String.valueOf(tmp) + ".0"; - } - else{ + } else { serviceVersion = component.getVersion(); } - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); format.setTimeZone(TimeZone.getTimeZone("UTC")); - Date date = new Date(); String releaseTime = format.format(date); - - if (component.getCategories() == null || component.getCategories().get(0) == null){ + if (component.getCategories() == null || component.getCategories().get(0) == null) { return; } - String serviceType = component.getCategories().get(0).getName(); String description = component.getDescription(); String serviceTemplate = DEFINITIONS_PATH + fileName; String hash = GeneralUtility.calculateMD5Base64EncodedByByteArray(mainYaml); - String nsMfBlock0 = createNsMfBlock0(serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate, hash); + String nsMfBlock0 = createNsMfBlock0(serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate, + hash); byte[] nsMfBlock0Byte = nsMfBlock0.getBytes(); zip.putNextEntry(new ZipEntry(Service_Manifest)); zip.write(nsMfBlock0Byte); } } - private Either fetchToscaRepresentation( - Component component, - boolean getFromCS, - ArtifactDefinition artifactDef - ) { + private Either fetchToscaRepresentation(Component component, boolean getFromCS, + ArtifactDefinition artifactDef) { LifecycleStateEnum lifecycleState = component.getLifecycleState(); - - boolean shouldBeFetchedFromCassandra = getFromCS || - !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || - lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - + boolean shouldBeFetchedFromCassandra = + getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); Either toscaRepresentation = - shouldBeFetchedFromCassandra ? - fetchToscaRepresentation(artifactDef) : - generateToscaRepresentation(component); - - return toscaRepresentation.left().bind(iff( - myd -> !myd.getDependencies().isDefined(), - myd -> fetchToscaTemplateDependencies(myd.getMainYaml(), component) - )); - } - - private static F> iff(Predicate p, Function> ifTrue) { - return l -> p.test(l) ? ifTrue.apply(l) : Either.left(l); + shouldBeFetchedFromCassandra ? fetchToscaRepresentation(artifactDef) : generateToscaRepresentation(component); + return toscaRepresentation.left() + .bind(iff(myd -> !myd.getDependencies().isDefined(), myd -> fetchToscaTemplateDependencies(myd.getMainYaml(), component))); } - private Either fetchToscaTemplateDependencies( - byte[] mainYml, - Component component - ) { + private Either fetchToscaTemplateDependencies(byte[] mainYml, Component component) { return toscaExportUtils.getDependencies(component).right().map(toscaError -> { - log.debug("Failed to retrieve dependencies for component {}, error {}", - component.getUniqueId(), toscaError); + log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), toscaError); return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError)); }).left().map(tt -> ToscaRepresentation.make(mainYml, tt)); } @@ -420,8 +529,7 @@ public class CsarUtils { if (dependency.getRight() instanceof Resource) { final Resource resource = (Resource) dependency.getRight(); if (CollectionUtils.isNotEmpty(resource.getDerivedList())) { - resource.getDerivedList().stream() - .filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node)) + resource.getDerivedList().stream().filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node)) .forEach(node -> nodes.add(node)); } } @@ -444,30 +552,23 @@ public class CsarUtils { while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) { zipEntry.append(new String(buffer, 0, read)); } - return (Map) new Yaml().load(zipEntry.toString()); } /** * Filters and removes all duplicated nodes found * - * @param nodesFromPackage a List of all derived nodes found on the given package + * @param nodesFromPackage a List of all derived nodes found on the given package * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra * @return a nodes Map updated */ - private Map updateNodeYml(final List nodesFromPackage, - final Map nodesFromArtifactFile) { - + private Map updateNodeYml(final List nodesFromPackage, final Map nodesFromArtifactFile) { if (MapUtils.isNotEmpty(nodesFromArtifactFile)) { final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName(); final Map nodeTypes = (Map) nodesFromArtifactFile.get(nodeTypeBlock); - nodesFromPackage.stream() - .filter(nodeTypes::containsKey) - .forEach(nodeTypes::remove); - + nodesFromPackage.stream().filter(nodeTypes::containsKey).forEach(nodeTypes::remove); nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes); } - return nodesFromArtifactFile; } @@ -475,63 +576,50 @@ public class CsarUtils { * Updates the zip entry from the given parameters * * @param byteArrayOutputStream an output stream in which the data is written into a byte array. - * @param nodesYaml a Map of nodes to be written + * @param nodesYaml a Map of nodes to be written */ - private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream, - final Map nodesYaml) throws IOException { + private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream, final Map nodesYaml) throws IOException { if (MapUtils.isNotEmpty(nodesYaml)) { byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes()); } } - private Either getZipOutputStreamResponseFormatEither( - ZipOutputStream zip, - List> dependencies - ) throws IOException { - - ComponentCache innerComponentsCache = ComponentCache - .overwritable(overwriteIfSameVersions()) - .onMerge((oldValue, newValue) -> { - log.warn("Overwriting component invariantID {} of version {} with a newer version {}", - oldValue.id, oldValue.getComponentVersion(), newValue.getComponentVersion() - ); - }); - + private Either getZipOutputStreamResponseFormatEither(ZipOutputStream zip, + List> dependencies) + throws IOException { + ComponentCache innerComponentsCache = ComponentCache.overwritable(overwriteIfSameVersions()).onMerge((oldValue, newValue) -> { + log.warn("Overwriting component invariantID {} of version {} with a newer version {}", oldValue.id, oldValue.getComponentVersion(), + newValue.getComponentVersion()); + }); if (dependencies != null && !dependencies.isEmpty()) { for (Triple d : dependencies) { String cassandraId = d.getMiddle(); Component childComponent = d.getRight(); - - Either entryData = getEntryData(cassandraId, childComponent) - .right().map(x -> componentsUtils.getResponseFormat(x)); - + Either entryData = getEntryData(cassandraId, childComponent).right() + .map(x -> componentsUtils.getResponseFormat(x)); if (entryData.isRight()) { return Either.right(entryData.right().value()); } - //fill innerComponentsCache String fileName = d.getLeft(); innerComponentsCache.put(cassandraId, fileName, childComponent); addInnerComponentsToCache(innerComponentsCache, childComponent); } - //add inner components to CSAR return addInnerComponentsToCSAR(zip, innerComponentsCache); } return null; } - private Either addInnerComponentsToCSAR( - ZipOutputStream zip, - ComponentCache innerComponentsCache - ) throws IOException { + private Either addInnerComponentsToCSAR(ZipOutputStream zip, ComponentCache innerComponentsCache) + throws IOException { for (ImmutableTriple ict : innerComponentsCache.iterable()) { Component innerComponent = ict.getRight(); - String icFileName = ict.getMiddle(); // add component to zip Either, ResponseFormat> zipEntry = toZipEntry(ict); // TODO: this should not be done, we should instead compose this either further, + // but in order to keep this refactoring small, we'll stop here. if (zipEntry.isRight()) { return Either.right(zipEntry.right().value()); @@ -547,36 +635,29 @@ public class CsarUtils { return null; } - private Either, ResponseFormat> toZipEntry( - ImmutableTriple cachedEntry - ) { + private Either, ResponseFormat> toZipEntry(ImmutableTriple cachedEntry) { String cassandraId = cachedEntry.getLeft(); String fileName = cachedEntry.getMiddle(); Component innerComponent = cachedEntry.getRight(); - return getEntryData(cassandraId, innerComponent) - .right().map(status -> { - log.debug("Failed adding to zip component {}, error {}", cassandraId, status); - return componentsUtils.getResponseFormat(status); - }).left().map(content -> new Tuple2<>(content, new ZipEntry(DEFINITIONS_PATH + fileName))); + return getEntryData(cassandraId, innerComponent).right().map(status -> { + log.debug("Failed adding to zip component {}, error {}", cassandraId, status); + return componentsUtils.getResponseFormat(status); + }).left().map(content -> new Tuple2<>(content, new ZipEntry(DEFINITIONS_PATH + fileName))); } /** * Writes to a CSAR zip from casandra schema data * - * @param zipOutputStream stores the input stream content - * @param schemaFileZip zip data from Cassandra + * @param zipOutputStream stores the input stream content + * @param schemaFileZip zip data from Cassandra * @param nodesFromPackage list of all nodes found on the onboarded package */ - private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream, - final byte[] schemaFileZip, - final List nodesFromPackage) { + private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream, final byte[] schemaFileZip, final List nodesFromPackage) { final int initSize = 2048; log.debug("Starting copy from Schema file zip to CSAR zip"); - try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); - final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - final BufferedOutputStream bufferedOutputStream = - new BufferedOutputStream(byteArrayOutputStream, initSize)) { - + try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream( + schemaFileZip)); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream( + byteArrayOutputStream, initSize)) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { ZipUtils.checkForZipSlipInRead(entry); @@ -607,58 +688,49 @@ public class CsarUtils { } /** - * Checks if the zip entry should or should not be added to the CSAR based on the given global type list + * Checks if the zip entry should or should not be added to the CSAR based on the given global type list * * @param entryName the zip entry name * @return true if the zip entry should be handled */ private boolean shouldZipEntryBeHandled(final String entryName) { - return ConfigurationManager.getConfigurationManager().getConfiguration() - .getGlobalCsarImports().stream() + return ConfigurationManager.getConfigurationManager().getConfiguration().getGlobalCsarImports().stream() .anyMatch(entry -> entry.contains(entryName)); } /** * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it. * - * @param zipInputStream the zip entry to be read + * @param zipInputStream the zip entry to be read * @param byteArrayOutputStream an output stream in which the data is written into a byte array. - * @param nodesFromPackage list of all nodes found on the onboarded package + * @param nodesFromPackage list of all nodes found on the onboarded package */ - private void handleNode(final ZipInputStream zipInputStream, - final ByteArrayOutputStream byteArrayOutputStream, + private void handleNode(final ZipInputStream zipInputStream, final ByteArrayOutputStream byteArrayOutputStream, final List nodesFromPackage) throws IOException { - final Map nodesFromArtifactFile = readYamlZipEntry(zipInputStream); final Map nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile); updateZipEntry(byteArrayOutputStream, nodesYaml); } private void addInnerComponentsToCache(ComponentCache componentCache, Component childComponent) { - javaListToVavrList(childComponent.getComponentInstances()) - .filter(ci -> componentCache.notCached(ci.getComponentUid())) - .forEach(ci -> { - // all resource must be only once! - Either resource = - toscaOperationFacade.getToscaElement(ci.getComponentUid()); - Component componentRI = checkAndAddComponent(componentCache, ci, resource); - //if not atomic - insert inner components as well - // TODO: This could potentially create a StackOverflowException if the call stack - // happens to be too large. Tail-recursive optimization should be used here. - if (!ModelConverter.isAtomicComponent(componentRI)) { - addInnerComponentsToCache(componentCache, componentRI); - } - }); + javaListToVavrList(childComponent.getComponentInstances()).filter(ci -> componentCache.notCached(ci.getComponentUid())).forEach(ci -> { + // all resource must be only once! + Either resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); + Component componentRI = checkAndAddComponent(componentCache, ci, resource); + //if not atomic - insert inner components as well + + // TODO: This could potentially create a StackOverflowException if the call stack + + // happens to be too large. Tail-recursive optimization should be used here. + if (!ModelConverter.isAtomicComponent(componentRI)) { + addInnerComponentsToCache(componentCache, componentRI); + } + }); } // TODO: Move this function in FJToVavrHelper.java once Change 108540 is merged - private io.vavr.collection.List javaListToVavrList( - List componentInstances - ) { - return Option - .of(componentInstances) - .map(io.vavr.collection.List::ofAll) - .getOrElse(io.vavr.collection.List::empty); + private io.vavr.collection.List javaListToVavrList(List componentInstances) { + return Option.of(componentInstances).map(io.vavr.collection.List::ofAll).getOrElse(io.vavr.collection.List::empty); } private Component checkAndAddComponent(ComponentCache componentCache, ComponentInstance ci, Either resource) { @@ -666,61 +738,35 @@ public class CsarUtils { log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName()); } Component componentRI = resource.left().value(); - Map childToscaArtifacts = componentRI.getToscaArtifacts(); ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); if (childArtifactDefinition != null) { //add to cache - componentCache.put( - childArtifactDefinition.getEsId(), - childArtifactDefinition.getArtifactName(), - componentRI - ); + componentCache.put(childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI); } return componentRI; } - private Either writeComponentInterface( - Component component, - ZipOutputStream zip, - String fileName, - boolean isAssociatedComponent - ) { + private Either writeComponentInterface(Component component, ZipOutputStream zip, String fileName, + boolean isAssociatedComponent) { // TODO: This should not be done but we need this to keep the refactoring small enough to be easily reviewable return writeComponentInterface(component, fileName, isAssociatedComponent, ZipWriter.live(zip)) - .map(void0 -> Either.left(zip)) - .recover(th -> { + .map(void0 -> Either.left(zip)).recover(th -> { log.error("#writeComponentInterface - zip writing failed with error: ", th); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); }).get(); } - private Try writeComponentInterface( - Component component, - String fileName, - boolean isAssociatedComponent, - ZipWriter zw - ) { - Either yml = toscaExportUtils - .exportComponentInterface(component, isAssociatedComponent) - .left().map(ToscaRepresentation::getMainYaml); - - return fromEither(yml, ToscaErrorException::new) - .flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName))); - } - - public static class ToscaErrorException extends Exception { - - ToscaErrorException(ToscaError error) { - super("Error while exporting component's interface (toscaError:" + error + ")"); - } + private Try writeComponentInterface(Component component, String fileName, boolean isAssociatedComponent, ZipWriter zw) { + Either yml = toscaExportUtils.exportComponentInterface(component, isAssociatedComponent).left() + .map(ToscaRepresentation::getMainYaml); + return fromEither(yml, ToscaErrorException::new).flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName))); } private Either getEntryData(String cassandraId, Component childComponent) { if (cassandraId == null || cassandraId.isEmpty()) { - return toscaExportUtils.exportComponent(childComponent) - .right().map(toscaErrorToActionStatus(childComponent)) - .left().map(ToscaRepresentation::getMainYaml); + return toscaExportUtils.exportComponent(childComponent).right().map(toscaErrorToActionStatus(childComponent)).left() + .map(ToscaRepresentation::getMainYaml); } else { return getFromCassandra(cassandraId); } @@ -728,55 +774,37 @@ public class CsarUtils { private F toscaErrorToActionStatus(Component childComponent) { return toscaError -> { - log.debug("Failed to export tosca template for child component {} error {}", - childComponent.getUniqueId(), toscaError); + log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), toscaError); return componentsUtils.convertFromToscaError(toscaError); }; } private Either getLatestSchemaFilesFromCassandra() { String fto = getVersionFirstThreeOctets(); - return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL) - .right().map(schemaFilesFetchDBError(fto)) - .left().bind(iff( - List::isEmpty, - () -> schemaFileFetchError(fto), - s -> Either.left(s.iterator().next().getPayloadAsArray()) - ) - ); - } - - private static F iff(Predicate
p, Supplier s, Function orElse) { - return a -> p.test(a) ? s.get() : orElse.apply(a); + return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL).right().map(schemaFilesFetchDBError(fto)).left() + .bind(iff(List::isEmpty, () -> schemaFileFetchError(fto), s -> Either.left(s.iterator().next().getPayloadAsArray()))); } private F schemaFilesFetchDBError(String firstThreeOctets) { return cos -> { - log.debug( - "Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.", - firstThreeOctets, CONFORMANCE_LEVEL); + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.", firstThreeOctets, + CONFORMANCE_LEVEL); StorageOperationStatus sos = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos); return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sos)); }; } private Either schemaFileFetchError(String firstThreeOctets) { - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", - firstThreeOctets, CONFORMANCE_LEVEL); - return Either.right( - componentsUtils.getResponseFormat( - ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL - ) - ); + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", firstThreeOctets, CONFORMANCE_LEVEL); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL)); } private Either getFromCassandra(String cassandraId) { - return artifactCassandraDao.getArtifact(cassandraId) - .right().map(cos -> { - log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos); - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos); - return componentsUtils.convertFromStorageResponse(storageStatus); - }).left().map(DAOArtifactData::getDataAsArray); + return artifactCassandraDao.getArtifact(cassandraId).right().map(cos -> { + log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos); + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos); + return componentsUtils.convertFromStorageResponse(storageStatus); + }).left().map(DAOArtifactData::getDataAsArray); } private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { @@ -787,297 +815,50 @@ public class CsarUtils { 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 String createNsMfBlock0(String serviceName, String createdBy, String serviceVersion, String releaseTime, - String serviceType, String description, String serviceTemplate, String hash) { - final String block0template = "metadata??\n" + - "ns_product_name: %s\n" + - "ns_provider_id: %s\n" + - "ns_package_version: %s\n" + + + private String createNsMfBlock0(String serviceName, String createdBy, String serviceVersion, String releaseTime, String serviceType, + String description, String serviceTemplate, String hash) { + final String block0template = "metadata??\n" + "ns_product_name: %s\n" + "ns_provider_id: %s\n" + "ns_package_version: %s\n" + //"ns_create_date_time: %s\n" + - "ns_release_data_time: %s\n" + - "ns_type: %s\n" + - "ns_package_description: %s\n\n" + - "Source: %s\n" + - "Algorithm: MD5\n" + - "Hash: %s\n\n"; - return String - .format(block0template, serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, - serviceTemplate, hash); + "ns_release_data_time: %s\n" + "ns_type: %s\n" + "ns_package_description: %s\n\n" + "Source: %s\n" + "Algorithm: MD5\n" + "Hash: %s\n\n"; + return String.format(block0template, serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate, hash); } - /** - * 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 -> - extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip -> - addExtractedVfcArtifact(ip, 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 - ) { - String vfcToscaNamespace = extractedVfcArtifact.getKey(); - - artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>()); - artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue()); - } - - private static Optional> extractVfcArtifact( - Entry entry, - Map>> collectedWarningMessages - ) { - String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER); - String groupType = parsedCsarArtifactPath[2].toUpperCase(); - - return detectArtifactGroupType(groupType, collectedWarningMessages) - .left() - .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath)) - .either( - ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)), - b -> Optional.empty() - ); - } - - 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 F buildArtifactDefinitionFromCsarArtifactPath( - Entry entry, - Map>> collectedWarningMessages, - String[] parsedCsarArtifactPath - ) { - return 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; - }; - } - - @Getter - public static final class NonMetaArtifactInfo { - @Setter - private String artifactUniqueId; - private final String path; - private final String artifactName; - private final String displayName; - private final String artifactLabel; - private final String artifactType; - private final ArtifactGroupTypeEnum artifactGroupType; - private final String payloadData; - private final String artifactChecksum; - private final boolean isFromCsar; - - public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType, - final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData, - final String artifactUniqueId, final 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 = null; - this.artifactChecksum = null; - } else { - this.payloadData = Base64.encodeBase64String(payloadData); - this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); - } - 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 - ) { - try { - String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER); - String groupType = parsedArtifactPath[1]; - String receivedTypeName = parsedArtifactPath[2]; - String artifactFileNameType = parsedArtifactPath[3]; - - return detectArtifactGroupType(groupType, collectedWarningMessages) - .left().bind(artifactGroupType -> { - String artifactType = - detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages); - - return Either.left(new NonMetaArtifactInfo( - artifactFileNameType, artifactPath, artifactType, - artifactGroupType, payloadData, null, true - )); - }); - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - return Either.right(false); - } - } - - 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(final ArtifactGroupTypeEnum artifactGroupType, - final String receivedTypeName, final String warningMessage, - final Map>> collectedWarningMessages, - final String... arguments) { - final ArtifactConfiguration artifactConfiguration = - ArtifactConfigManager.getInstance() - .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE) - .orElse(null); - - if (artifactConfiguration == null) { - final List messageArguments = new ArrayList<>(); - messageArguments.add(receivedTypeName); - messageArguments.addAll(Arrays.asList(arguments)); - if (!collectedWarningMessages.containsKey(warningMessage)) { - final Set> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - } - - return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName; - } - - private Either writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ + private Either writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, + ZipOutputStream zipstream, boolean isInCertificationRequest) + throws IOException { ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); - - Either writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedPath.isRight()){ + Either writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, + componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); + if (writeComponentArtifactsToSpecifiedPath.isRight()) { return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); } - ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedPath.isRight()){ + writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), + zipstream, ARTIFACTS_PATH, isInCertificationRequest); + if (writeComponentArtifactsToSpecifiedPath.isRight()) { return Either.right(writeComponentArtifactsToSpecifiedPath.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 + PATH_DELIMITER; - writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedPath.isRight()){ + writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, + isInCertificationRequest); + if (writeComponentArtifactsToSpecifiedPath.isRight()) { return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); } } writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream); - if (writeComponentArtifactsToSpecifiedPath.isRight()) { return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); } return Either.left(zipstream); } - private Either writeOperationsArtifactsToCsar(Component component, - ZipOutputStream zipstream) { + private Either writeOperationsArtifactsToCsar(Component component, ZipOutputStream zipstream) { if (checkComponentBeforeOperation(component)) { return Either.left(zipstream); } @@ -1096,48 +877,43 @@ public class CsarUtils { final String artifactName = operation.getImplementation().getArtifactName(); if (artifactFromCassandra.isRight()) { log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID); - log.error("Failed to get {} payload from DB reason: {}", artifactName, - artifactFromCassandra.right().value()); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource", - component.getUniqueId(), artifactName, artifactUUID)); + log.error("Failed to get {} payload from DB reason: {}", artifactName, artifactFromCassandra.right().value()); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource", component.getUniqueId(), + artifactName, artifactUUID)); } final byte[] payloadData = artifactFromCassandra.left().value(); - zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath( - component, null, operation, true))); + zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(component, null, operation, true))); zipstream.write(payloadData); } catch (IOException e) { - log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(), - interfaceEntry.getKey(), operation.getName()); + log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(), interfaceEntry.getKey(), + operation.getName()); log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e); - return Either.right(componentsUtils - .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource", - component.getUniqueId())); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource", component.getUniqueId())); } } } return Either.left(zipstream); } - private boolean checkComponentBeforeWrite(Component component, Entry interfaceEntry, OperationDataDefinition operation) { + private boolean checkComponentBeforeWrite(Component component, Entry interfaceEntry, + OperationDataDefinition operation) { final ArtifactDataDefinition implementation = operation.getImplementation(); if (Objects.isNull(implementation)) { - log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found", - component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), - operation.getName()); + log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found", component.getNormalizedName(), + interfaceEntry.getValue().getUniqueId(), operation.getName()); return true; } final String artifactName = implementation.getArtifactName(); if (Objects.isNull(artifactName)) { - log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found", - component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), - operation.getName()); + log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found", component.getNormalizedName(), + interfaceEntry.getValue().getUniqueId(), operation.getName()); return true; } if (OperationArtifactUtil.artifactNameIsALiteralValue(artifactName)) { log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact", - component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), - operation.getName()); + component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), operation.getName()); return true; } return false; @@ -1154,47 +930,42 @@ public class CsarUtils { return false; } - private Either writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, - String currentPath, boolean isInCertificationRequest) throws IOException { + private Either writeComponentArtifactsToSpecifiedPath(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 + PATH_DELIMITER; - Either writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeArtifactsInfoToSpecifiedPath.isRight()){ + Either writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, + componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); + if (writeArtifactsInfoToSpecifiedPath.isRight()) { return writeArtifactsInfoToSpecifiedPath; } } - return Either.left(zipstream); } private Either writeArtifactsInfoToSpecifiedPath(final Component mainComponent, - final ArtifactsInfo currArtifactsInfo, - final ZipOutputStream zip, - final String path, - final boolean isInCertificationRequest) throws IOException { - - final Map>> artifactsInfo = - currArtifactsInfo.getArtifactsInfo(); + final ArtifactsInfo currArtifactsInfo, + final ZipOutputStream zip, final String path, + final boolean isInCertificationRequest) throws IOException { + final Map>> artifactsInfo = currArtifactsInfo.getArtifactsInfo(); for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) { - final String groupTypeFolder = - path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER; - + final String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER; final Map> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); - for (final String artifactType : artifactTypesMap.keySet()) { final List artifactDefinitionList = artifactTypesMap.get(artifactType); String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER; - - if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path - .contains(ARTIFACTS_PATH + RESOURCES_PATH)) { + if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)) { // Ignore this packaging as BPMN artifacts needs to be packaged in different manner continue; } @@ -1205,12 +976,11 @@ public class CsarUtils { artifactTypeFolder = artifactTypeFolder .replace(ArtifactTypeEnum.ONBOARDED_PACKAGE.getType(), ArtifactTypeEnum.ETSI_PACKAGE.getType()); } - // TODO: We should not do this but in order to keep this refactoring small enough, + // we'll leave this as is for now - List collect = - filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest) - .collect(Collectors.toList()); + List collect = filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest) + .collect(Collectors.toList()); for (ArtifactDefinition ad : collect) { zip.putNextEntry(new ZipEntry(artifactTypeFolder + ad.getArtifactName())); zip.write(ad.getPayloadData()); @@ -1220,152 +990,36 @@ public class CsarUtils { return Either.left(zip); } - private Stream filterArtifactDefinitionToZip(Component mainComponent, - List artifactDefinitionList, boolean isInCertificationRequest) { - return artifactDefinitionList - .stream() - .filter(shouldBeInZip(isInCertificationRequest, mainComponent)) - .map(this::fetchPayLoadData) - .filter(Either::isLeft) - .map(e -> e.left().value()); + private Stream filterArtifactDefinitionToZip(Component mainComponent, List artifactDefinitionList, + boolean isInCertificationRequest) { + return artifactDefinitionList.stream().filter(shouldBeInZip(isInCertificationRequest, mainComponent)).map(this::fetchPayLoadData) + .filter(Either::isLeft).map(e -> e.left().value()); } private Predicate shouldBeInZip(boolean isInCertificationRequest, Component component) { - return artifactDefinition -> - !(!isInCertificationRequest - && component.isService() - && artifactDefinition.isHeatEnvType() - || artifactDefinition.hasNoMandatoryEsId()); + return artifactDefinition -> !(!isInCertificationRequest && component.isService() && artifactDefinition.isHeatEnvType() || artifactDefinition + .hasNoMandatoryEsId()); } private Either fetchPayLoadData(ArtifactDefinition ad) { byte[] payloadData = ad.getPayloadData(); - if(payloadData == null) { - return getFromCassandra(ad.getEsId()) - .left().map(pd -> { - ad.setPayload(pd); - return ad; - }).right().map(as -> { - log.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId()); - log.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as); - return as; - }); + if (payloadData == null) { + return getFromCassandra(ad.getEsId()).left().map(pd -> { + ad.setPayload(pd); + return ad; + }).right().map(as -> { + log.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId()); + log.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as); + return as; + }); } else { return Either.left(ad); } } - /************************************ 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 void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup, - Map> artifactsDefinition) { - if (artifactsInfoField.get(artifactGroup) == null) { - artifactsInfoField.put(artifactGroup, artifactsDefinition); - } else { - Map> artifactTypeEnumListMap = - artifactsInfoField.get(artifactGroup); - artifactTypeEnumListMap.putAll(artifactsDefinition); - artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap); - } - - } - - public boolean isEmpty() { - return artifactsInfoField.isEmpty(); - } - - public boolean isNotEmpty() { - return !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 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; - } - - } - - 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){ + private Either collectComponentCsarDefinition(Component component) { ComponentArtifacts componentArtifacts = new ComponentArtifacts(); Component updatedComponent = component; @@ -1373,7 +1027,7 @@ public class CsarUtils { if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { Either getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); - if(getServiceResponse.isRight()){ + if (getServiceResponse.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); return Either.right(componentsUtils.getResponseFormat(actionStatus)); } @@ -1387,22 +1041,23 @@ public class CsarUtils { componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); - Map resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) + 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){ + 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()){ + updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); + if (collectComponentInstanceArtifacts.isRight()) { return Either.right(collectComponentInstanceArtifacts.right().value()); } } } - if(log.isDebugEnabled()){ - printResult(componentArtifacts,updatedComponent.getName()); + if (log.isDebugEnabled()) { + printResult(componentArtifacts, updatedComponent.getName()); } return Either.left(new CsarDefinition(componentArtifacts)); @@ -1414,23 +1069,25 @@ public class CsarUtils { ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); printArtifacts(componentInstanceArtifacts); result.append("Type Artifacts\n"); - for (Map.Entry typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ + for (Map.Entry typeArtifacts : componentArtifacts.getComponentTypeArtifacts().entrySet()) { result.append("Folder " + typeArtifacts.getKey() + "\n"); result.append(printArtifacts(typeArtifacts.getValue())); } - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug(result.toString()); } } + /************************************ Artifacts Structure ******************************************************************/ + private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { StringBuilder result = new StringBuilder(); ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); Map>> componentArtifacts = artifactsInfo.getArtifactsInfo(); printArtifacts(componentArtifacts); result = result.append("Resources\n"); - for (Map.Entry resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ + for (Map.Entry resourceInstance : componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()) { result.append("Folder" + resourceInstance.getKey() + "\n"); result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); } @@ -1440,11 +1097,11 @@ public class CsarUtils { private String printArtifacts(Map>> componetArtifacts) { StringBuilder result = new StringBuilder(); - for (Map.Entry>> artifactGroup:componetArtifacts.entrySet()){ + for (Map.Entry>> artifactGroup : componetArtifacts.entrySet()) { result.append(" " + artifactGroup.getKey().getType()); - for (Map.Entry> groupArtifacts:artifactGroup.getValue().entrySet()){ + for (Map.Entry> groupArtifacts : artifactGroup.getValue().entrySet()) { result.append(" " + groupArtifacts.getKey()); - for (ArtifactDefinition artifact:groupArtifacts.getValue()){ + for (ArtifactDefinition artifact : groupArtifacts.getValue()) { result.append(" " + artifact.getArtifactDisplayName()); } } @@ -1464,24 +1121,24 @@ public class CsarUtils { return componentArtifactsInfo; } - private Either collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, - Map resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { + private Either collectComponentInstanceArtifacts(Component parentComponent, ComponentInstance componentInstance, + Map resourcesTypeArtifacts, + ComponentTypeArtifacts instanceArtifactsLocation) { //1. get the component instance component String componentUid; if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { - componentUid = componentInstance.getSourceModelUid(); - } - else { - componentUid = componentInstance.getComponentUid(); - } + componentUid = componentInstance.getSourceModelUid(); + } else { + componentUid = componentInstance.getComponentUid(); + } Either component = toscaOperationFacade.getToscaElement(componentUid); - if (component.isRight()) { - log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); + if (component.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)); + parentComponent.getComponentType().getValue(), parentComponent.getUUID(), + componentInstance.getOriginType().getComponentType().getValue(), componentUid)); } - Component fetchedComponent = component.left().value(); + Component fetchedComponent = component.left().value(); //2. fill the artifacts for the current component parent type String toscaComponentName = @@ -1498,31 +1155,31 @@ public class CsarUtils { //3. find the artifacts specific to the instance Map> componentInstanceSpecificInformationalArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); + getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); Map> componentInstanceSpecificDeploymentArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); + getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); //4. add the instances artifacts to the component type ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ + if (!componentInstanceSpecificInformationalArtifacts.isEmpty()) { artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); } - if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ + if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()) { artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); } - if (!artifactsInfo.isEmpty()){ + 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){ + if (componentInstances != null) { + for (ComponentInstance childComponentInstance : componentInstances) { Either collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ + fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); + if (collectComponentInstanceArtifacts.isRight()) { return collectComponentInstanceArtifacts; } } @@ -1538,21 +1195,24 @@ public class CsarUtils { public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) { this.versionFirstThreeOctets = versionFirstThreeOctetes; } + 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>> componentTypeArtifacts, + ArtifactGroupTypeEnum artifactGroupTypeEnum) { + Map> parentArtifacts = componentTypeArtifacts + .get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance Map> artifactsByTypeOfComponentInstance = new HashMap<>(); - if (componentArtifacts!=null){ - for (ArtifactDefinition artifact:componentArtifacts.values()){ + if (componentArtifacts != null) { + for (ArtifactDefinition artifact : componentArtifacts.values()) { List parentArtifactsByType = null; - if (parentArtifacts!=null){ + if (parentArtifacts != null) { parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType()); } //the artifact is of instance - if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ + if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)) { List typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType()); - if (typeArtifacts == null){ + if (typeArtifacts == null) { typeArtifacts = new ArrayList<>(); artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts); } @@ -1569,23 +1229,23 @@ public class CsarUtils { Map> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); Map deploymentArtifacts = component.getDeploymentArtifacts(); Map> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); - Map interfaceOperationArtifacts = - OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component); - Map> interfaceOperationArtifactsByType = collectGroupArtifacts( - interfaceOperationArtifacts); + Map interfaceOperationArtifacts = + OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component); + Map> interfaceOperationArtifactsByType = collectGroupArtifacts( + interfaceOperationArtifacts); ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!informationalArtifactsByType.isEmpty()){ + if (!informationalArtifactsByType.isEmpty()) { artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); } - if (!deploymentArtifactsByType.isEmpty() ){ + if (!deploymentArtifactsByType.isEmpty()) { artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); - } + } return artifactsInfo; } private Map> collectGroupArtifacts( - final Map componentArtifacts) { + final Map componentArtifacts) { final Map> artifactsByType = new HashMap<>(); for (final ArtifactDefinition artifact : componentArtifacts.values()) { if (artifact.getArtifactUUID() != null) { @@ -1596,4 +1256,160 @@ public class CsarUtils { } return artifactsByType; } + + public static class ToscaErrorException extends Exception { + + ToscaErrorException(ToscaError error) { + super("Error while exporting component's interface (toscaError:" + error + ")"); + } + } + + @Getter + public static final class NonMetaArtifactInfo { + + private final String path; + private final String artifactName; + private final String displayName; + private final String artifactLabel; + private final String artifactType; + private final ArtifactGroupTypeEnum artifactGroupType; + private final String payloadData; + private final String artifactChecksum; + private final boolean isFromCsar; + @Setter + private String artifactUniqueId; + + public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType, + final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData, final String artifactUniqueId, + final 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 = null; + this.artifactChecksum = null; + } else { + this.payloadData = Base64.encodeBase64String(payloadData); + this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); + } + this.artifactUniqueId = artifactUniqueId; + } + } + + /** + * 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 void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup, Map> artifactsDefinition) { + if (artifactsInfoField.get(artifactGroup) == null) { + artifactsInfoField.put(artifactGroup, artifactsDefinition); + } else { + Map> artifactTypeEnumListMap = artifactsInfoField.get(artifactGroup); + artifactTypeEnumListMap.putAll(artifactsDefinition); + artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap); + } + } + + public boolean isEmpty() { + return artifactsInfoField.isEmpty(); + } + + public boolean isNotEmpty() { + return !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 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; + } + } + + 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; + } + } } + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/FJToVavrHelper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/FJToVavrHelper.java index 32b9957beb..94bc279cfe 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/FJToVavrHelper.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/FJToVavrHelper.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; import io.vavr.control.Try; @@ -28,9 +27,11 @@ import java.util.function.Function; */ public final class FJToVavrHelper { - private FJToVavrHelper() {} + private FJToVavrHelper() { + } public interface Try0 { + /** * Converts a {@link fj.data.Either} to a {@link io.vavr.control.Try} * @@ -39,10 +40,7 @@ public final class FJToVavrHelper { * @return */ static Try fromEither(fj.data.Either e, Function onError) { - return e.either( - Try::success, - r -> Try.failure(onError.apply(r)) - ); + return e.either(Try::success, r -> Try.failure(onError.apply(r))); } } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParser.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParser.java index c579a6510c..4c41d22d55 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParser.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParser.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. @@ -17,19 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; +import java.util.Map; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate; -import java.util.Map; - public interface GroupExportParser { - Map getGroups(Component component); - - ToscaGroupTemplate getToscaGroupTemplate(GroupInstance groupInstance, String invariantName) ; - + Map getGroups(Component component); + + ToscaGroupTemplate getToscaGroupTemplate(GroupInstance groupInstance, String invariantName); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java index bb4d363e43..65f3b64c33 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.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. @@ -17,10 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.apache.commons.collections.MapUtils.isEmpty; +import static org.apache.commons.collections.MapUtils.isNotEmpty; +import static org.apache.commons.lang.StringUtils.isNotEmpty; +import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getComponentInstanceNameByInstanceId; + import fj.data.Either; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.function.Supplier; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; @@ -43,234 +58,182 @@ import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; - -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.function.Supplier; import org.springframework.context.event.EventListener; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toMap; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.apache.commons.collections.MapUtils.isEmpty; -import static org.apache.commons.collections.MapUtils.isNotEmpty; -import static org.apache.commons.lang.StringUtils.isNotEmpty; -import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getComponentInstanceNameByInstanceId; - @org.springframework.stereotype.Component public class GroupExportParserImpl implements GroupExportParser { private static final Logger log = Logger.getLogger(GroupExportParserImpl.class); - + private final PropertyConvertor propertyConvertor; private Map dataTypes; private ApplicationDataTypeCache dataTypeCache; - private final PropertyConvertor propertyConvertor; - - @Autowired - public GroupExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) { - this.dataTypeCache = dataTypeCache; - this.propertyConvertor = propertyConvertor; - this.dataTypes = getDataTypes(); - } - - private Map getDataTypes() { - Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); - throw new SdcResourceNotFoundException(); - } - - return dataTypesEither.left().value(); - } - @EventListener - public void onDataTypesCacheChangedEvent( - ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) { - dataTypes = dataTypesCacheChangedEvent.getNewData(); - log.debug("Data types cache updated."); - } - - @Override - public Map getGroups(Component component) { - List groups = component.getGroups(); - - if (isEmpty(groups)) { - return null; - } - - return groups.stream() - .collect(toMap(GroupDefinition::getName, - group -> getToscaGroupTemplate(component, group))); - } - - @Override - public ToscaGroupTemplate getToscaGroupTemplate(GroupInstance groupInstance, String componentInstanceInvariantName) { - - String groupName = groupInstance.getName(); - if (StringUtils.isNotEmpty(componentInstanceInvariantName)) { - String prefix = componentInstanceInvariantName + Constants.GROUP_POLICY_NAME_DELIMETER; - if (groupName.startsWith(prefix)) { - groupName = groupName.substring(prefix.length()); - } - } - String invariantUUID = groupInstance.getInvariantUUID(); - String groupUUID = groupInstance.getGroupUUID(); - String version = groupInstance.getVersion(); - List groupInstanceProperties = groupInstance.convertToGroupInstancesProperties(); - String groupType = groupInstance.getType(); - String customizationUUID = groupInstance.getCustomizationUUID(); - - IToscaMetadata toscaMetadata = getToscaGroupTemplateMetadata(groupName, invariantUUID, groupUUID, version, groupType, customizationUUID); - Map properties = getToscaGroupTemplateProperties(groupInstanceProperties); - + @Autowired + public GroupExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) { + this.dataTypeCache = dataTypeCache; + this.propertyConvertor = propertyConvertor; + this.dataTypes = getDataTypes(); + } + + private Map getDataTypes() { + Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); + throw new SdcResourceNotFoundException(); + } + return dataTypesEither.left().value(); + } + + @EventListener + public void onDataTypesCacheChangedEvent(ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) { + dataTypes = dataTypesCacheChangedEvent.getNewData(); + log.debug("Data types cache updated."); + } + + @Override + public Map getGroups(Component component) { + List groups = component.getGroups(); + if (isEmpty(groups)) { + return null; + } + return groups.stream().collect(toMap(GroupDefinition::getName, group -> getToscaGroupTemplate(component, group))); + } + + @Override + public ToscaGroupTemplate getToscaGroupTemplate(GroupInstance groupInstance, String componentInstanceInvariantName) { + String groupName = groupInstance.getName(); + if (StringUtils.isNotEmpty(componentInstanceInvariantName)) { + String prefix = componentInstanceInvariantName + Constants.GROUP_POLICY_NAME_DELIMETER; + if (groupName.startsWith(prefix)) { + groupName = groupName.substring(prefix.length()); + } + } + String invariantUUID = groupInstance.getInvariantUUID(); + String groupUUID = groupInstance.getGroupUUID(); + String version = groupInstance.getVersion(); + List groupInstanceProperties = groupInstance.convertToGroupInstancesProperties(); + String groupType = groupInstance.getType(); + String customizationUUID = groupInstance.getCustomizationUUID(); + IToscaMetadata toscaMetadata = getToscaGroupTemplateMetadata(groupName, invariantUUID, groupUUID, version, groupType, customizationUUID); + Map properties = getToscaGroupTemplateProperties(groupInstanceProperties); return new ToscaGroupTemplate(groupType, toscaMetadata, properties); - } - - private ToscaGroupTemplate getToscaGroupTemplate(Component component, GroupDefinition groupDefinition) { - - String groupName = groupDefinition.getName(); - String invariantUUID = groupDefinition.getInvariantUUID(); - String groupUUID = groupDefinition.getGroupUUID(); - String version = groupDefinition.getVersion(); - String groupType = groupDefinition.getType(); - List groupDefinitionProperties = groupDefinition.getProperties(); - - List members = getToscaGroupTemplateMembers(component, groupDefinition.getMembers()); - IToscaMetadata toscaMetadata = getToscaGroupTemplateMetadata(groupName, invariantUUID, groupUUID, version,groupType, null); - Map properties = getToscaGroupTemplateProperties(groupDefinitionProperties); - Map capabilities = getToscaGroupTemplateCapabilities(groupDefinition); - - return new ToscaGroupTemplate(groupType, members, toscaMetadata, properties, capabilities); - } - - private Map getToscaGroupTemplateCapabilities(GroupDefinition group) { - if (isEmpty(group.getCapabilities())) { - return null; - } - - Map toscaGroupTemplateCapabilities = group.getCapabilities().values() - .stream() - .flatMap(Collection::stream) - .filter(c -> isNotEmptyProperties(c.getProperties())) - .collect(toMap(c-> getCapabilityName(c, group), this::getToscaTemplateCapability)); - - if (isNotEmpty(toscaGroupTemplateCapabilities)) { - return toscaGroupTemplateCapabilities; - } else { - return null; - } - } - - private String getCapabilityName(CapabilityDefinition capability, GroupDefinition group) { - if(ComponentUtilities.isNotUpdatedCapReqName(group.getNormalizedName() + ".", capability.getName(), capability.getPreviousName())){ - return capability.getName(); - } - return capability.getPreviousName(); - } - - private boolean isNotEmptyProperties(List properties) { - return isNotEmpty(properties) && properties.stream() - .filter(isComponentInstancePropertiesNotEmpty()) - .findFirst() - .isPresent(); - } - - private ToscaTemplateCapability getToscaTemplateCapability(CapabilityDefinition capability) { - ToscaTemplateCapability toscaTemplateCapability = new ToscaTemplateCapability(); - Map toscaCapabilityProperties = capability.getProperties().stream() - .filter(isComponentInstancePropertiesNotEmpty()) - .collect(toMap(ComponentInstanceProperty::getName, - this::fetchCapabilityValue)); - if(isNotEmpty(toscaCapabilityProperties)) { - toscaTemplateCapability.setProperties(toscaCapabilityProperties); - } - return toscaTemplateCapability; - } - - private Predicate isComponentInstancePropertiesNotEmpty() { - return c -> { - return (c.getName() != null && (c.getValue() != null || c.getDefaultValue() != null)); - }; - } - - private String fetchCapabilityValue(ComponentInstanceProperty componentInstanceProperty) { - if(componentInstanceProperty.getValue() != null) { - return componentInstanceProperty.getValue(); - }else { - return componentInstanceProperty.getDefaultValue(); - } - } - - private List getToscaGroupTemplateMembers(Component component, Map members) { - if (members == null) { - return null; - } - return members.values() - .stream() - .map(memberId -> getMemberNameByMemberId(component, memberId)) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(toList()); - } - - private Optional getMemberNameByMemberId(Component component, String memberId) { - return getComponentInstanceNameByInstanceId(component, memberId); - } - - private IToscaMetadata getToscaGroupTemplateMetadata(String groupName,String invariantUUID, - String groupUUID,String version,String type, String customizationUUID) { - - IToscaMetadata toscaMetadata = getToscaMetadataByType(type); - - toscaMetadata.setName(groupName); - toscaMetadata.setInvariantUUID(invariantUUID); - toscaMetadata.setUUID(groupUUID); - toscaMetadata.setVersion(version); - toscaMetadata.setCustomizationUUID(customizationUUID); - return toscaMetadata; - } - - private IToscaMetadata getToscaMetadataByType(String type) { - IToscaMetadata toscaMetadata; - if (GroupUtils.isVfModule(type)) { - toscaMetadata = new VfModuleToscaMetadata(); - } else { - toscaMetadata = new ToscaMetadata(); - } - return toscaMetadata; - } - - private Map getToscaGroupTemplateProperties(List tempProperties) { - - if (isEmpty(tempProperties)) { - return null; - } - - Map props = new HashMap<>(); - - tempProperties.forEach(input -> - propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input)) - ); - - if (props.isEmpty()) { - return null; - } else { - return props; - } - } - - private Supplier getPropertyValue(PropertyDataDefinition propertyDataDefinition) { - return () -> { - if (isNotEmpty(propertyDataDefinition.getValue())) { - return propertyDataDefinition.getValue(); - } else { - return propertyDataDefinition.getDefaultValue(); - } - }; - } + } + + private ToscaGroupTemplate getToscaGroupTemplate(Component component, GroupDefinition groupDefinition) { + String groupName = groupDefinition.getName(); + String invariantUUID = groupDefinition.getInvariantUUID(); + String groupUUID = groupDefinition.getGroupUUID(); + String version = groupDefinition.getVersion(); + String groupType = groupDefinition.getType(); + List groupDefinitionProperties = groupDefinition.getProperties(); + List members = getToscaGroupTemplateMembers(component, groupDefinition.getMembers()); + IToscaMetadata toscaMetadata = getToscaGroupTemplateMetadata(groupName, invariantUUID, groupUUID, version, groupType, null); + Map properties = getToscaGroupTemplateProperties(groupDefinitionProperties); + Map capabilities = getToscaGroupTemplateCapabilities(groupDefinition); + return new ToscaGroupTemplate(groupType, members, toscaMetadata, properties, capabilities); + } + + private Map getToscaGroupTemplateCapabilities(GroupDefinition group) { + if (isEmpty(group.getCapabilities())) { + return null; + } + Map toscaGroupTemplateCapabilities = group.getCapabilities().values().stream().flatMap(Collection::stream) + .filter(c -> isNotEmptyProperties(c.getProperties())).collect(toMap(c -> getCapabilityName(c, group), this::getToscaTemplateCapability)); + if (isNotEmpty(toscaGroupTemplateCapabilities)) { + return toscaGroupTemplateCapabilities; + } else { + return null; + } + } + + private String getCapabilityName(CapabilityDefinition capability, GroupDefinition group) { + if (ComponentUtilities.isNotUpdatedCapReqName(group.getNormalizedName() + ".", capability.getName(), capability.getPreviousName())) { + return capability.getName(); + } + return capability.getPreviousName(); + } + + private boolean isNotEmptyProperties(List properties) { + return isNotEmpty(properties) && properties.stream().filter(isComponentInstancePropertiesNotEmpty()).findFirst().isPresent(); + } + + private ToscaTemplateCapability getToscaTemplateCapability(CapabilityDefinition capability) { + ToscaTemplateCapability toscaTemplateCapability = new ToscaTemplateCapability(); + Map toscaCapabilityProperties = capability.getProperties().stream().filter(isComponentInstancePropertiesNotEmpty()) + .collect(toMap(ComponentInstanceProperty::getName, this::fetchCapabilityValue)); + if (isNotEmpty(toscaCapabilityProperties)) { + toscaTemplateCapability.setProperties(toscaCapabilityProperties); + } + return toscaTemplateCapability; + } + + private Predicate isComponentInstancePropertiesNotEmpty() { + return c -> { + return (c.getName() != null && (c.getValue() != null || c.getDefaultValue() != null)); + }; + } + + private String fetchCapabilityValue(ComponentInstanceProperty componentInstanceProperty) { + if (componentInstanceProperty.getValue() != null) { + return componentInstanceProperty.getValue(); + } else { + return componentInstanceProperty.getDefaultValue(); + } + } + + private List getToscaGroupTemplateMembers(Component component, Map members) { + if (members == null) { + return null; + } + return members.values().stream().map(memberId -> getMemberNameByMemberId(component, memberId)).filter(Optional::isPresent).map(Optional::get) + .collect(toList()); + } + + private Optional getMemberNameByMemberId(Component component, String memberId) { + return getComponentInstanceNameByInstanceId(component, memberId); + } + + private IToscaMetadata getToscaGroupTemplateMetadata(String groupName, String invariantUUID, String groupUUID, String version, String type, + String customizationUUID) { + IToscaMetadata toscaMetadata = getToscaMetadataByType(type); + toscaMetadata.setName(groupName); + toscaMetadata.setInvariantUUID(invariantUUID); + toscaMetadata.setUUID(groupUUID); + toscaMetadata.setVersion(version); + toscaMetadata.setCustomizationUUID(customizationUUID); + return toscaMetadata; + } + + private IToscaMetadata getToscaMetadataByType(String type) { + IToscaMetadata toscaMetadata; + if (GroupUtils.isVfModule(type)) { + toscaMetadata = new VfModuleToscaMetadata(); + } else { + toscaMetadata = new ToscaMetadata(); + } + return toscaMetadata; + } + + private Map getToscaGroupTemplateProperties(List tempProperties) { + if (isEmpty(tempProperties)) { + return null; + } + Map props = new HashMap<>(); + tempProperties.forEach(input -> propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input))); + if (props.isEmpty()) { + return null; + } else { + return props; + } + } + + private Supplier getPropertyValue(PropertyDataDefinition propertyDataDefinition) { + return () -> { + if (isNotEmpty(propertyDataDefinition.getValue())) { + return propertyDataDefinition.getValue(); + } else { + return propertyDataDefinition.getDefaultValue(); + } + }; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/InterfacesOperationsConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/InterfacesOperationsConverter.java index 8d35517d92..37659f1bd3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/InterfacesOperationsConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/InterfacesOperationsConverter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.tosca; import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DEFAULT; @@ -59,17 +58,13 @@ import org.springframework.stereotype.Service; @Service public class InterfacesOperationsConverter { - + public static final String SELF = "SELF"; private static final String DERIVED_FROM_STANDARD_INTERFACE = "tosca.interfaces.node.lifecycle.Standard"; private static final String DERIVED_FROM_BASE_DEFAULT = "org.openecomp.interfaces.node.lifecycle."; - private static final String DEFAULT_HAS_UNDERSCORE = "_default"; private static final String DOT = "."; private static final String DEFAULTP = "defaultp"; - - public static final String SELF = "SELF"; private static final String LOCAL_INTERFACE_TYPE = "Local"; - private final PropertyConvertor propertyConvertor; @Autowired @@ -91,18 +86,15 @@ public class InterfacesOperationsConverter { if (MapUtils.isEmpty(interfaces)) { return null; } - Map toscaInterfaceTypes = new HashMap<>(); for (InterfaceDefinition interfaceDefinition : interfaces.values()) { - boolean isInterfaceTypeExistInGlobalType = - allInterfaceTypes.stream().anyMatch(type -> type.equalsIgnoreCase(interfaceDefinition.getType())); + boolean isInterfaceTypeExistInGlobalType = allInterfaceTypes.stream() + .anyMatch(type -> type.equalsIgnoreCase(interfaceDefinition.getType())); if (!isInterfaceTypeExistInGlobalType) { ToscaInterfaceNodeType toscaInterfaceType = new ToscaInterfaceNodeType(); toscaInterfaceType.setDerived_from(DERIVED_FROM_STANDARD_INTERFACE); - final Map operations = interfaceDefinition.getOperations(); Map toscaOperations = new HashMap<>(); - for (Map.Entry operationEntry : operations.entrySet()) { toscaOperations.put(operationEntry.getValue().getName(), null); } @@ -110,22 +102,100 @@ public class InterfacesOperationsConverter { Map interfacesAsMap = getObjectAsMap(toscaInterfaceType); Map operationsMap = (Map) interfacesAsMap.remove(OPERATIONS.getElementName()); interfacesAsMap.putAll(operationsMap); - toscaInterfaceTypes.put(getInterfaceType(component, LOCAL_INTERFACE_TYPE), interfacesAsMap); } } return MapUtils.isNotEmpty(toscaInterfaceTypes) ? toscaInterfaceTypes : null; } + private static Object getDefaultValue(Map inputValueMap) { + Object defaultValue = null; + for (Map.Entry operationEntry : inputValueMap.entrySet()) { + final Object value = operationEntry.getValue(); + if (value instanceof Map) { + getDefaultValue((Map) value); + } + final String key = operationEntry.getKey(); + if (key.equals(DEFAULTP)) { + defaultValue = inputValueMap.remove(key); + } + } + return defaultValue; + } + + //Remove input type and copy default value directly into the proxy node template from the node type + private static void handleOperationInputValue(Map operationsMap, String parentKey) { + for (Map.Entry operationEntry : operationsMap.entrySet()) { + final Object value = operationEntry.getValue(); + final String key = operationEntry.getKey(); + if (value instanceof Map) { + if (INPUTS.getElementName().equals(parentKey)) { + Object defaultValue = getDefaultValue((Map) value); + operationsMap.put(key, defaultValue); + } else { + handleOperationInputValue((Map) value, key); + } + } + } + } + + private static String getLastPartOfName(String toscaResourceName) { + return toscaResourceName.substring(toscaResourceName.lastIndexOf(DOT) + 1); + } + + private static boolean isArtifactPresent(Map.Entry operationEntry) { + final boolean isImplementationPresent = !Objects.isNull(operationEntry.getValue().getImplementation()); + if (isImplementationPresent) { + return !Objects.isNull(operationEntry.getValue().getImplementation().getArtifactName()); + } + return false; + } + + private static String getInputValue(String inputValue) { + String toscaInputValue = inputValue; + if (Objects.nonNull(inputValue) && inputValue.contains(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName())) { + Gson gson = new Gson(); + Map> consumptionValue = gson.fromJson(inputValue, Map.class); + List mappedOutputValue = consumptionValue.get(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName()); + //Extract the interface name from the interface type + String interfaceType = mappedOutputValue.get(1); + String interfaceName = interfaceType.substring(interfaceType.lastIndexOf('.') + 1); + mappedOutputValue.remove(1); + mappedOutputValue.add(1, interfaceName); + toscaInputValue = gson.toJson(consumptionValue); + } + return toscaInputValue; + } + + private static String getInterfaceType(Component component, String interfaceType) { + if (LOCAL_INTERFACE_TYPE.equals(interfaceType)) { + return DERIVED_FROM_BASE_DEFAULT + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + } + return interfaceType; + } + + private static Map getObjectAsMap(Object obj) { + ObjectMapper objectMapper = new ObjectMapper(); + if (obj instanceof ToscaInterfaceDefinition) { + //Prevent empty field serialization in interface definition + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + Map objectAsMap = obj instanceof Map ? (Map) obj : objectMapper.convertValue(obj, Map.class); + final String defaultEntry = DEFAULT.getElementName(); + if (objectAsMap.containsKey(defaultEntry)) { + objectAsMap.put(DEFAULT_HAS_UNDERSCORE, objectAsMap.remove(defaultEntry)); + } + return objectAsMap; + } + /** * Adds the 'interfaces' element to the node type provided. * * @param component to work on * @param nodeType to which the interfaces element will be added */ - public void addInterfaceDefinitionElement(Component component, ToscaNodeType nodeType, - Map dataTypes, - boolean isAssociatedComponent) { + public void addInterfaceDefinitionElement(Component component, ToscaNodeType nodeType, Map dataTypes, + boolean isAssociatedComponent) { if (component instanceof Product) { return; } @@ -133,60 +203,47 @@ public class InterfacesOperationsConverter { if (MapUtils.isEmpty(interfaces)) { return; } - Map toscaInterfaceDefinitions = getInterfacesMap(component, dataTypes, - isAssociatedComponent); + Map toscaInterfaceDefinitions = getInterfacesMap(component, dataTypes, isAssociatedComponent); if (MapUtils.isNotEmpty(toscaInterfaceDefinitions)) { nodeType.setInterfaces(toscaInterfaceDefinitions); } } - private Map getInterfacesMap(Component component, - Map dataTypes, - boolean isAssociatedComponent) { + private Map getInterfacesMap(Component component, Map dataTypes, boolean isAssociatedComponent) { return getInterfacesMap(component, null, component.getInterfaces(), dataTypes, isAssociatedComponent, false); } - public Map getInterfacesMap(final Component component, - final ComponentInstance componentInstance, - final Map interfaces, - final Map dataTypes, - final boolean isAssociatedComponent, - final boolean isServiceProxyInterface) { + public Map getInterfacesMap(final Component component, final ComponentInstance componentInstance, + final Map interfaces, final Map dataTypes, + final boolean isAssociatedComponent, final boolean isServiceProxyInterface) { if (MapUtils.isEmpty(interfaces)) { return null; } - final Map toscaInterfaceDefinitions = new HashMap<>(); for (InterfaceDefinition interfaceDefinition : interfaces.values()) { - handleInterfaceOperations(component, componentInstance, dataTypes, isAssociatedComponent, - isServiceProxyInterface, toscaInterfaceDefinitions, interfaceDefinition); + handleInterfaceOperations(component, componentInstance, dataTypes, isAssociatedComponent, isServiceProxyInterface, + toscaInterfaceDefinitions, interfaceDefinition); } return toscaInterfaceDefinitions; } - public Map getInterfacesMapFromComponentInstance(final Component component, - final ComponentInstance componentInstance, + public Map getInterfacesMapFromComponentInstance(final Component component, final ComponentInstance componentInstance, final Map dataTypes, - final boolean isAssociatedComponent, - final boolean isServiceProxyInterface) { + final boolean isAssociatedComponent, final boolean isServiceProxyInterface) { final Map toscaInterfaceDefinitions = new HashMap<>(); final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); for (final Map.Entry interfaceEntry : componentInstance.getInterfaces().entrySet()) { - final InterfaceDefinition interfaceDefinition = objectMapper - .convertValue(interfaceEntry.getValue(), InterfaceDefinition.class); - handleInterfaceOperations(component, componentInstance, dataTypes, isAssociatedComponent, - isServiceProxyInterface, toscaInterfaceDefinitions, interfaceDefinition); + final InterfaceDefinition interfaceDefinition = objectMapper.convertValue(interfaceEntry.getValue(), InterfaceDefinition.class); + handleInterfaceOperations(component, componentInstance, dataTypes, isAssociatedComponent, isServiceProxyInterface, + toscaInterfaceDefinitions, interfaceDefinition); } return toscaInterfaceDefinitions; } - private void handleInterfaceOperations(final Component component, - final ComponentInstance componentInstance, - final Map dataTypes, - final boolean isAssociatedComponent, - final boolean isServiceProxyInterface, - final Map toscaInterfaceDefinitions, + private void handleInterfaceOperations(final Component component, final ComponentInstance componentInstance, + final Map dataTypes, final boolean isAssociatedComponent, + final boolean isServiceProxyInterface, final Map toscaInterfaceDefinitions, final InterfaceDefinition interfaceDefinition) { final String interfaceType; if (componentInstance != null && LOCAL_INTERFACE_TYPE.equals(interfaceDefinition.getType())) { @@ -200,19 +257,14 @@ public class InterfacesOperationsConverter { } final Map operations = interfaceDefinition.getOperations(); final Map toscaOperationMap = new HashMap<>(); - for (final Entry operationEntry : operations.entrySet()) { - final ToscaLifecycleOperationDefinition toscaLifecycleOperationDefinition = - new ToscaLifecycleOperationDefinition(); - handleInterfaceOperationImplementation(component, componentInstance, isAssociatedComponent, - operationEntry, + final ToscaLifecycleOperationDefinition toscaLifecycleOperationDefinition = new ToscaLifecycleOperationDefinition(); + handleInterfaceOperationImplementation(component, componentInstance, isAssociatedComponent, operationEntry, toscaLifecycleOperationDefinition); toscaLifecycleOperationDefinition.setDescription(operationEntry.getValue().getDescription()); - fillToscaOperationInputs(operationEntry.getValue(), dataTypes, toscaLifecycleOperationDefinition, - isServiceProxyInterface); + fillToscaOperationInputs(operationEntry.getValue(), dataTypes, toscaLifecycleOperationDefinition, isServiceProxyInterface); toscaOperationMap.put(operationEntry.getValue().getName(), toscaLifecycleOperationDefinition); } - toscaInterfaceDefinition.setOperations(toscaOperationMap); final Map interfaceInputMap = createInterfaceInputMap(interfaceDefinition, dataTypes); if (!interfaceInputMap.isEmpty()) { @@ -222,26 +274,20 @@ public class InterfacesOperationsConverter { if (interfaceDefinitionAsMap.containsKey(INPUTS.getElementName())) { handleDefaults((Map) interfaceDefinitionAsMap.get(INPUTS.getElementName())); } - final Map operationsMap = - (Map) interfaceDefinitionAsMap.remove(OPERATIONS.getElementName()); - + final Map operationsMap = (Map) interfaceDefinitionAsMap.remove(OPERATIONS.getElementName()); handleOperationInputValue(operationsMap, interfaceType); - interfaceDefinitionAsMap.putAll(operationsMap); toscaInterfaceDefinitions.put(getLastPartOfName(interfaceType), interfaceDefinitionAsMap); } - private void handleInterfaceOperationImplementation(final Component component, - final ComponentInstance componentInstance, + private void handleInterfaceOperationImplementation(final Component component, final ComponentInstance componentInstance, final boolean isAssociatedComponent, final Entry operationEntry, final ToscaLifecycleOperationDefinition toscaOperation) { final String operationArtifactPath; - if (isArtifactPresent(operationEntry) && StringUtils - .isNotEmpty(operationEntry.getValue().getImplementation().getArtifactName())) { + if (isArtifactPresent(operationEntry) && StringUtils.isNotEmpty(operationEntry.getValue().getImplementation().getArtifactName())) { operationArtifactPath = OperationArtifactUtil - .createOperationArtifactPath(component, componentInstance, operationEntry.getValue(), - isAssociatedComponent); + .createOperationArtifactPath(component, componentInstance, operationEntry.getValue(), isAssociatedComponent); toscaOperation.setImplementation(operationArtifactPath); } else { toscaOperation.setImplementation(operationEntry.getValue().getImplementation().getArtifactName()); @@ -252,18 +298,17 @@ public class InterfacesOperationsConverter { if (MapUtils.isEmpty(interfaceMap)) { return; } - final Set emptyInterfaces = interfaceMap.entrySet().stream() - .filter(entry -> { - final Object value = entry.getValue(); - if (value instanceof ToscaInterfaceDefinition) { - final ToscaInterfaceDefinition interfaceDefinition = (ToscaInterfaceDefinition) value; - return MapUtils.isEmpty(interfaceDefinition.getOperations()); - } else if (value instanceof Map) { - final Map interfaceDefMap = (Map) value; - return MapUtils.isEmpty(interfaceDefMap); - } - return false; - }).map(Entry::getKey).collect(Collectors.toSet()); + final Set emptyInterfaces = interfaceMap.entrySet().stream().filter(entry -> { + final Object value = entry.getValue(); + if (value instanceof ToscaInterfaceDefinition) { + final ToscaInterfaceDefinition interfaceDefinition = (ToscaInterfaceDefinition) value; + return MapUtils.isEmpty(interfaceDefinition.getOperations()); + } else if (value instanceof Map) { + final Map interfaceDefMap = (Map) value; + return MapUtils.isEmpty(interfaceDefMap); + } + return false; + }).map(Entry::getKey).collect(Collectors.toSet()); emptyInterfaces.forEach(interfaceMap::remove); } @@ -283,37 +328,6 @@ public class InterfacesOperationsConverter { return toscaInterfaceInputMap; } - private static Object getDefaultValue(Map inputValueMap) { - Object defaultValue = null; - for (Map.Entry operationEntry : inputValueMap.entrySet()) { - final Object value = operationEntry.getValue(); - if (value instanceof Map) { - getDefaultValue((Map) value); - } - final String key = operationEntry.getKey(); - if (key.equals(DEFAULTP)) { - defaultValue = inputValueMap.remove(key); - } - } - return defaultValue; - } - - //Remove input type and copy default value directly into the proxy node template from the node type - private static void handleOperationInputValue(Map operationsMap, String parentKey) { - for (Map.Entry operationEntry : operationsMap.entrySet()) { - final Object value = operationEntry.getValue(); - final String key = operationEntry.getKey(); - if (value instanceof Map) { - if (INPUTS.getElementName().equals(parentKey)) { - Object defaultValue = getDefaultValue((Map) value); - operationsMap.put(key, defaultValue); - } else { - handleOperationInputValue((Map) value, key); - } - } - } - } - /* * workaround for : currently "defaultp" is not being converted to "default" by the relevant code in * ToscaExportHandler so, any string Map key named "defaultp" will have its named changed to "default" @@ -333,87 +347,26 @@ public class InterfacesOperationsConverter { } } - private static String getLastPartOfName(String toscaResourceName) { - return toscaResourceName.substring(toscaResourceName.lastIndexOf(DOT) + 1); - } - - private static boolean isArtifactPresent(Map.Entry operationEntry) { - final boolean isImplementationPresent = !Objects.isNull(operationEntry.getValue().getImplementation()); - if (isImplementationPresent) { - return !Objects.isNull(operationEntry.getValue().getImplementation().getArtifactName()); - } - return false; - } - - private void fillToscaOperationInputs(OperationDataDefinition operation, - Map dataTypes, - ToscaLifecycleOperationDefinition toscaOperation, - boolean isServiceProxyInterface) { + private void fillToscaOperationInputs(OperationDataDefinition operation, Map dataTypes, + ToscaLifecycleOperationDefinition toscaOperation, boolean isServiceProxyInterface) { if (Objects.isNull(operation.getInputs()) || operation.getInputs().isEmpty()) { toscaOperation.setInputs(null); return; } Map toscaInputs = new HashMap<>(); - for (OperationInputDefinition input : operation.getInputs().getListToscaDataDefinition()) { ToscaProperty toscaInput = new ToscaProperty(); toscaInput.setDescription(input.getDescription()); toscaInput.setType(input.getType()); toscaInput.setRequired(input.isRequired()); if (isServiceProxyInterface) { - String inputValue = Objects.nonNull(input.getValue()) ? getInputValue(input.getValue()) : - getInputValue(input.getToscaDefaultValue()); + String inputValue = Objects.nonNull(input.getValue()) ? getInputValue(input.getValue()) : getInputValue(input.getToscaDefaultValue()); toscaInput.setDefaultp(propertyConvertor.convertToToscaObject(input, inputValue, dataTypes, false)); } else { - toscaInput.setDefaultp(propertyConvertor - .convertToToscaObject(input, getInputValue(input.getToscaDefaultValue()), - dataTypes, false)); + toscaInput.setDefaultp(propertyConvertor.convertToToscaObject(input, getInputValue(input.getToscaDefaultValue()), dataTypes, false)); } toscaInputs.put(input.getName(), toscaInput); } toscaOperation.setInputs(toscaInputs); } - - private static String getInputValue(String inputValue) { - String toscaInputValue = inputValue; - if (Objects.nonNull(inputValue) && inputValue.contains(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName())) { - Gson gson = new Gson(); - Map> consumptionValue = gson.fromJson(inputValue, Map.class); - List mappedOutputValue = - consumptionValue.get(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName()); - //Extract the interface name from the interface type - String interfaceType = mappedOutputValue.get(1); - String interfaceName = interfaceType.substring(interfaceType.lastIndexOf('.') + 1); - mappedOutputValue.remove(1); - mappedOutputValue.add(1, interfaceName); - toscaInputValue = gson.toJson(consumptionValue); - } - return toscaInputValue; - } - - private static String getInterfaceType(Component component, String interfaceType) { - if (LOCAL_INTERFACE_TYPE.equals(interfaceType)) { - return DERIVED_FROM_BASE_DEFAULT - + component.getComponentMetadataDefinition() - .getMetadataDataDefinition().getSystemName(); - } - - return interfaceType; - } - - private static Map getObjectAsMap(Object obj) { - ObjectMapper objectMapper = new ObjectMapper(); - if (obj instanceof ToscaInterfaceDefinition) { - //Prevent empty field serialization in interface definition - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - } - Map objectAsMap = - obj instanceof Map ? (Map) obj : objectMapper.convertValue(obj, Map.class); - - final String defaultEntry = DEFAULT.getElementName(); - if (objectAsMap.containsKey(defaultEntry)) { - objectAsMap.put(DEFAULT_HAS_UNDERSCORE, objectAsMap.remove(defaultEntry)); - } - return objectAsMap; - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParser.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParser.java index d4a3504f1d..e6e5ccdc44 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParser.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParser.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. @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; +import java.util.Map; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate; -import java.util.Map; - public interface PolicyExportParser { - Map getPolicies(Component component); + Map getPolicies(Component component); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java index 598f73f9ee..d544d34b66 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.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. @@ -17,11 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.apache.commons.collections.MapUtils.isNotEmpty; +import static org.apache.commons.lang.StringUtils.isNotEmpty; import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; @@ -37,181 +46,138 @@ import org.openecomp.sdc.be.tosca.model.ToscaMetadata; import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; -import java.util.stream.Collectors; import org.springframework.context.event.EventListener; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.apache.commons.collections.MapUtils.isNotEmpty; -import static org.apache.commons.lang.StringUtils.isNotEmpty; - @org.springframework.stereotype.Component public class PolicyExportParserImpl implements PolicyExportParser { - private static final Logger log = Logger.getLogger(PolicyExportParserImpl.class); - - private ApplicationDataTypeCache dataTypeCache; - private Map dataTypes; - private PropertyConvertor propertyConvertor; - - @Autowired - public PolicyExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) { - this.dataTypeCache = dataTypeCache; - this.propertyConvertor = propertyConvertor; - this.dataTypes = getDataTypes(); - } - - private Map getDataTypes() { - Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); - throw new SdcResourceNotFoundException(); - } - - return dataTypesEither.left().value(); - } - - @EventListener - public void onDataTypesCacheChangedEvent( - ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) { - dataTypes = dataTypesCacheChangedEvent.getNewData(); - log.debug("Data types cache updated."); - } - - @Override - public Map getPolicies(Component component) { - Map toscaPolicies = null; - Map policies = component.getPolicies(); - if (isNotEmpty(policies)) { - - toscaPolicies = policies.values().stream().collect( - Collectors.toMap( - PolicyDefinition::getName, - policy->getToscaPolicyTemplate(policy,component))); - log.debug("policies converted"); - } - return toscaPolicies; - } - - private ToscaPolicyTemplate getToscaPolicyTemplate(PolicyDefinition policyDefinition,Component component) { - - String type = policyDefinition.getPolicyTypeName(); - IToscaMetadata metadata = getToscaPolicyTemplateMetadata(policyDefinition); - Map properties = getToscaPolicyTemplateProperties(policyDefinition); - List targets = getToscaPolicyTemplateTargets( - policyDefinition,component.getComponentInstances(),component.getGroups()); - - return new ToscaPolicyTemplate(type, metadata, properties, targets); - } - - private List getToscaPolicyTemplateTargets(PolicyDefinition policyDefinition, - List componentInstances, List groups) { - - Map> targets = policyDefinition.getTargets(); - List targetNames = null; - - if (targets == null || targets.isEmpty()) { - return null; - } - - List componentInstancesTargets = targets.get(PolicyTargetType.COMPONENT_INSTANCES); - List groupTargets = targets.get(PolicyTargetType.GROUPS); - - if (isNotEmpty(componentInstancesTargets) && isNotEmpty(componentInstances)) { - // get target names by Id from component instances - Map targetNamesByIdFromComponentInstances = - getTargetNamesByIdFromComponentInstances(componentInstances); - targetNames = targetNamesLazyInstantiation(targetNames); - addTargetNames(componentInstancesTargets, targetNames, targetNamesByIdFromComponentInstances); - - } - - if (isNotEmpty(groupTargets) && isNotEmpty(groups)) { - // get target names by id from group definitions - Map targetNamesByIdFromGroupDefinitions = getTargetNamesByIdFromGroupDefinitions(groups); - targetNames = targetNamesLazyInstantiation(targetNames); - addTargetNames(groupTargets, targetNames, targetNamesByIdFromGroupDefinitions); - - } - - return targetNames; - } - - private List targetNamesLazyInstantiation(List targetNames) { - if (targetNames == null) { - targetNames = new ArrayList<>(); - } - return targetNames; - } - - private void addTargetNames(List targets, List targetNames, - Map targetNamesById) { - - if (!targetNamesById.isEmpty()) { - - for (String id : targets) { - String name = targetNamesById.get(id); - if (name != null) { - targetNames.add(name); - } - } - } - } - - private Map getTargetNamesByIdFromGroupDefinitions(List groups) { - return groups.stream().collect( - Collectors.toMap(GroupDefinition::getUniqueId, GroupDefinition::getName)); - } - - private Map getTargetNamesByIdFromComponentInstances(List componentInstances) { - return componentInstances.stream().collect( - Collectors.toMap(ComponentInstance::getUniqueId,ComponentInstance::getName)); - } - - private Map getToscaPolicyTemplateProperties(PolicyDefinition policyDefinition) { - - List tempProperties = policyDefinition.getProperties(); - - if (isEmpty(tempProperties)) { - return null; - } - - Map props = new HashMap<>(); - - tempProperties.forEach(input -> - propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input)) - ); - - if (props.isEmpty()) { - return null; - } else { - return props; - } - } - - private Supplier getPropertyValue(PropertyDataDefinition propertyDataDefinition) { - return () -> { - if (isNotEmpty(propertyDataDefinition.getValue())) { - return propertyDataDefinition.getValue(); - } else { - return propertyDataDefinition.getDefaultValue(); - } - }; - } - - private IToscaMetadata getToscaPolicyTemplateMetadata(PolicyDefinition policyDefinition) { - IToscaMetadata metadata = new ToscaMetadata(); - metadata.setInvariantUUID(policyDefinition.getInvariantUUID()); - metadata.setUUID(policyDefinition.getPolicyUUID()); - metadata.setName(policyDefinition.getName()); - metadata.setVersion(policyDefinition.getVersion()); - return metadata; - } - + private static final Logger log = Logger.getLogger(PolicyExportParserImpl.class); + private ApplicationDataTypeCache dataTypeCache; + private Map dataTypes; + private PropertyConvertor propertyConvertor; + + @Autowired + public PolicyExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) { + this.dataTypeCache = dataTypeCache; + this.propertyConvertor = propertyConvertor; + this.dataTypes = getDataTypes(); + } + + private Map getDataTypes() { + Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); + throw new SdcResourceNotFoundException(); + } + return dataTypesEither.left().value(); + } + + @EventListener + public void onDataTypesCacheChangedEvent(ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) { + dataTypes = dataTypesCacheChangedEvent.getNewData(); + log.debug("Data types cache updated."); + } + + @Override + public Map getPolicies(Component component) { + Map toscaPolicies = null; + Map policies = component.getPolicies(); + if (isNotEmpty(policies)) { + toscaPolicies = policies.values().stream() + .collect(Collectors.toMap(PolicyDefinition::getName, policy -> getToscaPolicyTemplate(policy, component))); + log.debug("policies converted"); + } + return toscaPolicies; + } + + private ToscaPolicyTemplate getToscaPolicyTemplate(PolicyDefinition policyDefinition, Component component) { + String type = policyDefinition.getPolicyTypeName(); + IToscaMetadata metadata = getToscaPolicyTemplateMetadata(policyDefinition); + Map properties = getToscaPolicyTemplateProperties(policyDefinition); + List targets = getToscaPolicyTemplateTargets(policyDefinition, component.getComponentInstances(), component.getGroups()); + return new ToscaPolicyTemplate(type, metadata, properties, targets); + } + + private List getToscaPolicyTemplateTargets(PolicyDefinition policyDefinition, List componentInstances, + List groups) { + Map> targets = policyDefinition.getTargets(); + List targetNames = null; + if (targets == null || targets.isEmpty()) { + return null; + } + List componentInstancesTargets = targets.get(PolicyTargetType.COMPONENT_INSTANCES); + List groupTargets = targets.get(PolicyTargetType.GROUPS); + if (isNotEmpty(componentInstancesTargets) && isNotEmpty(componentInstances)) { + // get target names by Id from component instances + Map targetNamesByIdFromComponentInstances = getTargetNamesByIdFromComponentInstances(componentInstances); + targetNames = targetNamesLazyInstantiation(targetNames); + addTargetNames(componentInstancesTargets, targetNames, targetNamesByIdFromComponentInstances); + } + if (isNotEmpty(groupTargets) && isNotEmpty(groups)) { + // get target names by id from group definitions + Map targetNamesByIdFromGroupDefinitions = getTargetNamesByIdFromGroupDefinitions(groups); + targetNames = targetNamesLazyInstantiation(targetNames); + addTargetNames(groupTargets, targetNames, targetNamesByIdFromGroupDefinitions); + } + return targetNames; + } + + private List targetNamesLazyInstantiation(List targetNames) { + if (targetNames == null) { + targetNames = new ArrayList<>(); + } + return targetNames; + } + + private void addTargetNames(List targets, List targetNames, Map targetNamesById) { + if (!targetNamesById.isEmpty()) { + for (String id : targets) { + String name = targetNamesById.get(id); + if (name != null) { + targetNames.add(name); + } + } + } + } + + private Map getTargetNamesByIdFromGroupDefinitions(List groups) { + return groups.stream().collect(Collectors.toMap(GroupDefinition::getUniqueId, GroupDefinition::getName)); + } + + private Map getTargetNamesByIdFromComponentInstances(List componentInstances) { + return componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getUniqueId, ComponentInstance::getName)); + } + + private Map getToscaPolicyTemplateProperties(PolicyDefinition policyDefinition) { + List tempProperties = policyDefinition.getProperties(); + if (isEmpty(tempProperties)) { + return null; + } + Map props = new HashMap<>(); + tempProperties.forEach(input -> propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input))); + if (props.isEmpty()) { + return null; + } else { + return props; + } + } + + private Supplier getPropertyValue(PropertyDataDefinition propertyDataDefinition) { + return () -> { + if (isNotEmpty(propertyDataDefinition.getValue())) { + return propertyDataDefinition.getValue(); + } else { + return propertyDataDefinition.getDefaultValue(); + } + }; + } + + private IToscaMetadata getToscaPolicyTemplateMetadata(PolicyDefinition policyDefinition) { + IToscaMetadata metadata = new ToscaMetadata(); + metadata.setInvariantUUID(policyDefinition.getInvariantUUID()); + metadata.setUUID(policyDefinition.getPolicyUUID()); + metadata.setName(policyDefinition.getName()); + metadata.setVersion(policyDefinition.getVersion()); + return metadata; + } } 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 59b859dae2..89ff754933 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; import com.google.gson.JsonElement; @@ -38,41 +37,35 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.DataTypePropertyConverter; import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter; import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter; import org.openecomp.sdc.be.model.tosca.converters.ToscaValueConverter; -import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition; import org.openecomp.sdc.be.tosca.model.ToscaNodeType; import org.openecomp.sdc.be.tosca.model.ToscaProperty; +import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition; import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.springframework.stereotype.Service; @Service public class PropertyConvertor { - private JsonParser jsonParser = new JsonParser(); - private static final Logger log = Logger.getLogger(PropertyConvertor.class); - public enum PropertyType { - CAPABILITY, - INPUT, - PROPERTY - } - - public Either convertProperties(Component component, ToscaNodeType toscaNodeType, Map dataTypes) { + private static final Logger log = Logger.getLogger(PropertyConvertor.class); + private JsonParser jsonParser = new JsonParser(); + 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, PropertyType.PROPERTY)); - }); + }); if (!properties.isEmpty()) { toscaNodeType.setProperties(properties); } @@ -83,7 +76,8 @@ public class PropertyConvertor { public ToscaProperty convertProperty(Map dataTypes, PropertyDefinition property, PropertyType propertyType) { ToscaProperty prop = new ToscaProperty(); - log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue()); + log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), + property.getDefaultValue()); SchemaDefinition schema = property.getSchema(); if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) { final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition(); @@ -92,7 +86,7 @@ public class PropertyConvertor { prop.setEntry_schema(toscaSchemaDefinition); } String defaultValue = property.getDefaultValue(); - if(Objects.isNull(defaultValue)) { + if (Objects.isNull(defaultValue)) { defaultValue = property.getValue(); } Object convertedObj = convertToToscaObject(property, defaultValue, dataTypes, false); @@ -102,21 +96,21 @@ public class PropertyConvertor { prop.setType(property.getType()); prop.setDescription(property.getDescription()); prop.setRequired(property.isRequired()); - if(propertyType.equals(PropertyType.CAPABILITY)) { + if (propertyType.equals(PropertyType.CAPABILITY)) { prop.setStatus(property.getStatus()); } prop.setMetadata(property.getMetadata()); return prop; } - - public Object convertToToscaObject(PropertyDataDefinition property, String value, Map dataTypes, boolean preserveEmptyValue) { + public Object convertToToscaObject(PropertyDataDefinition property, String value, Map dataTypes, + boolean preserveEmptyValue) { String propertyType = property.getType(); String innerType = property.getSchemaType(); 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)){ + if (StringUtils.isEmpty(value)) { return null; } } @@ -124,7 +118,6 @@ public class PropertyConvertor { 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"); @@ -132,7 +125,6 @@ public class PropertyConvertor { 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(); @@ -144,24 +136,19 @@ public class PropertyConvertor { if (typeIfScalar == null) { isScalar = false; } - innerConverter = type.getValueConverter(); if (ToscaPropertyType.STRING == 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(); @@ -178,7 +165,7 @@ public class PropertyConvertor { } } Object convertedValue; - if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) { + if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) { convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); } else if (isScalar) { // complex json for scalar type @@ -186,33 +173,31 @@ public class PropertyConvertor { } else if (innerConverter != null) { convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); } else { - convertedValue = mapConverterInst.convertDataTypeToToscaObject( - innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue); + convertedValue = mapConverterInst + .convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue); } - 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 void convertAndAddValue(Map dataTypes, - Map props, PropertyDataDefinition prop, Supplier supplier) { + public void convertAndAddValue(Map dataTypes, Map props, PropertyDataDefinition prop, + Supplier supplier) { Object convertedValue = convertValue(dataTypes, prop, supplier); if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { props.put(prop.getName(), convertedValue); } } - private Object convertValue(Map dataTypes, - T input, Supplier supplier) { + private Object convertValue(Map dataTypes, T input, Supplier supplier) { return convertToToscaObject(input, supplier.get(), dataTypes, false); } + + public enum PropertyType {CAPABILITY, INPUT, PROPERTY} } 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 c3acb43186..af0fc06a29 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 @@ -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. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; public enum ToscaError { - 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 9664ccd510..988f709bfc 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; @@ -142,9 +141,17 @@ import org.yaml.snakeyaml.representer.Representer; @org.springframework.stereotype.Component("tosca-export-handler") public class ToscaExportHandler { + public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; private static final Logger log = Logger.getLogger(ToscaExportHandler.class); private static final String INVARIANT_UUID = "invariantUUID"; - + private static final String TOSCA_VERSION = "tosca_simple_yaml_1_3"; + private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; + private static final String IMPORTS_FILE_KEY = "file"; + private static final String TOSCA_INTERFACE_NAME = "-interface.yml"; + 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 {}"; + private static final String NATIVE_ROOT = "tosca.nodes.Root"; + private static final YamlUtil yamlUtil = new YamlUtil(); private ApplicationDataTypeCache dataTypeCache; private ToscaOperationFacade toscaOperationFacade; private CapabilityRequirementConverter capabilityRequirementConverter; @@ -157,14 +164,10 @@ public class ToscaExportHandler { private InterfacesOperationsConverter interfacesOperationsConverter; @Autowired - public ToscaExportHandler(final ApplicationDataTypeCache dataTypeCache, - final ToscaOperationFacade toscaOperationFacade, - final CapabilityRequirementConverter capabilityRequirementConverter, - final PolicyExportParser policyExportParser, - final GroupExportParser groupExportParser, - final PropertyConvertor propertyConvertor, - final InputConverter inputConverter, - final OutputConverter outputConverter, + public ToscaExportHandler(final ApplicationDataTypeCache dataTypeCache, final ToscaOperationFacade toscaOperationFacade, + final CapabilityRequirementConverter capabilityRequirementConverter, final PolicyExportParser policyExportParser, + final GroupExportParser groupExportParser, final PropertyConvertor propertyConvertor, + final InputConverter inputConverter, final OutputConverter outputConverter, final InterfaceLifecycleOperation interfaceLifecycleOperation, final InterfacesOperationsConverter interfacesOperationsConverter) { this.dataTypeCache = dataTypeCache; @@ -179,28 +182,28 @@ public class ToscaExportHandler { this.interfacesOperationsConverter = interfacesOperationsConverter; } - private static final String TOSCA_VERSION = "tosca_simple_yaml_1_3"; - private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; - private static final String IMPORTS_FILE_KEY = "file"; - private static final String TOSCA_INTERFACE_NAME = "-interface.yml"; - public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; - 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 {}"; - private static final String NATIVE_ROOT = "tosca.nodes.Root"; - private static final YamlUtil yamlUtil = new YamlUtil(); + public static String getInterfaceFilename(String artifactName) { + return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; + } + + private static void removeOperationImplementationForProxyNodeType(Map proxyComponentInterfaces) { + if (MapUtils.isEmpty(proxyComponentInterfaces)) { + return; + } + proxyComponentInterfaces.values().stream().map(InterfaceDataDefinition::getOperations).filter(MapUtils::isNotEmpty) + .forEach(operations -> operations.values().forEach(operation -> operation.setImplementation(null))); + } public Either exportComponent(Component component) { return convertToToscaTemplate(component).left().map(this::createToscaRepresentation); } - public Either exportComponentInterface(final Component component, - final boolean isAssociatedComponent) { + public Either exportComponentInterface(final Component component, final boolean isAssociatedComponent) { final List>> defaultToscaImportConfig = getDefaultToscaImportConfig(); if (CollectionUtils.isEmpty(defaultToscaImportConfig)) { log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); return Either.right(ToscaError.GENERAL_ERROR); } - String toscaVersion = null; if (component instanceof Resource) { toscaVersion = ((Resource) component).getToscaVersion(); @@ -208,12 +211,11 @@ public class ToscaExportHandler { ToscaTemplate toscaTemplate = new ToscaTemplate(toscaVersion != null ? toscaVersion : TOSCA_VERSION); toscaTemplate.setImports(new ArrayList<>(defaultToscaImportConfig)); final Map nodeTypes = new HashMap<>(); - final Either toscaTemplateRes = - convertInterfaceNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes, isAssociatedComponent); + final Either toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes, + isAssociatedComponent); if (toscaTemplateRes.isRight()) { return Either.right(toscaTemplateRes.right().value()); } - toscaTemplate = toscaTemplateRes.left().value(); ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); return Either.left(toscaRepresentation); @@ -224,29 +226,22 @@ public class ToscaExportHandler { 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()); - return ToscaRepresentation.make(sb.toString().getBytes(), toscaTemplate); } public Either getDependencies(Component component) { ToscaTemplate toscaTemplate = new ToscaTemplate(null); - Either>, ToscaError> fillImports = fillImports(component, - toscaTemplate); + Either>, ToscaError> fillImports = fillImports(component, toscaTemplate); if (fillImports.isRight()) { return Either.right(fillImports.right().value()); } @@ -275,43 +270,34 @@ public class ToscaExportHandler { log.trace("convert component as topology template"); return convertToscaTemplate(component, toscaTemplate); } - } private Either convertToscaTemplate(Component component, ToscaTemplate toscaNode) { - - Either>, ToscaError> importsRes = fillImports(component, - 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); + 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()); + 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); } - createServiceSubstitutionNodeTypes(componentCache, component, toscaNode); - Either, ToscaError> proxyInterfaceTypesEither = createProxyInterfaceTypes(component); if (proxyInterfaceTypesEither.isRight()) { - log.debug("Failed to populate service proxy local interface types in tosca, error {}", - nodeTypesMapEither.right().value()); + log.debug("Failed to populate service proxy local interface types in tosca, error {}", nodeTypesMapEither.right().value()); return Either.right(proxyInterfaceTypesEither.right().value()); } Map proxyInterfaceTypes = proxyInterfaceTypesEither.left().value(); if (MapUtils.isNotEmpty(proxyInterfaceTypes)) { toscaNode.setInterface_types(proxyInterfaceTypes); } - Either, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); @@ -321,24 +307,20 @@ public class ToscaExportHandler { ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); List inputDef = component.getInputs(); Map inputs = inputConverter.convertInputs(inputDef, dataTypes); - if (!inputs.isEmpty()) { topologyTemplate.setInputs(inputs); } - final Map outputs; try { outputs = outputConverter.convert(component.getOutputs(), dataTypes); } catch (final ToscaConversionException e) { log.error(EcompLoggerErrorCode.SCHEMA_ERROR, ToscaExportHandler.class.getName(), - "Could not parse component '{}' outputs. Component unique id '{}'.", - new Object[]{component.getName(), component.getUniqueId(), e}); + "Could not parse component '{}' outputs. Component unique id '{}'.", new Object[]{component.getName(), component.getUniqueId(), e}); return Either.right(ToscaError.GENERAL_ERROR); } if (!outputs.isEmpty()) { topologyTemplate.setOutputs(outputs); } - final List componentInstances = component.getComponentInstances(); Map> componentInstancesProperties = component.getComponentInstancesProperties(); Map> componentInstanceInterfaces = component.getComponentInstancesInterfaces(); @@ -351,46 +333,39 @@ public class ToscaExportHandler { log.debug("node templates converted"); topologyTemplate.setNode_templates(nodeTemplates.left().value()); } - final Map relationshipTemplatesMap = - new ToscaExportRelationshipTemplatesHandler().createFrom(topologyTemplate.getNode_templates()); + final Map relationshipTemplatesMap = new ToscaExportRelationshipTemplatesHandler() + .createFrom(topologyTemplate.getNode_templates()); if (!relationshipTemplatesMap.isEmpty()) { topologyTemplate.setRelationshipTemplates(relationshipTemplatesMap); } - SubstitutionMapping substitutionMapping = new SubstitutionMapping(); convertSubstitutionMappingFilter(component, substitutionMapping); - addGroupsToTopologyTemplate(component, topologyTemplate); - try { addPoliciesToTopologyTemplate(component, topologyTemplate); } catch (SdcResourceNotFoundException e) { log.debug("Fail to add policies to topology template:", e); return Either.right(ToscaError.GENERAL_ERROR); } - String toscaResourceName; switch (component.getComponentType()) { case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() - .getMetadataDataDefinition()).getToscaResourceName(); + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()) + .getToscaResourceName(); break; case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX - + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + 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); + Either capabilities = convertCapabilities(component, substitutionMapping, componentCache); if (capabilities.isRight()) { return Either.right(capabilities.right().value()); } substitutionMapping = capabilities.left().value(); - Either requirements = capabilityRequirementConverter .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping); if (requirements.isRight()) { @@ -401,25 +376,18 @@ public class ToscaExportHandler { if (!propertyMappingMap.isEmpty()) { substitutionMapping.setProperties(propertyMappingMap); } - final Map attributesMappingMap = buildSubstitutionMappingAttributesMapping(component); if (!attributesMappingMap.isEmpty()) { substitutionMapping.setAttributes(attributesMappingMap); } - topologyTemplate.setSubstitution_mappings(substitutionMapping); - toscaNode.setTopology_template(topologyTemplate); - return Either.left(toscaNode); } - private void convertSubstitutionMappingFilter(final Component component, - final SubstitutionMapping substitutionMapping) { - if (component.getSubstitutionFilter() != null - && (component.getSubstitutionFilter().getProperties()).getListToscaDataDefinition() != null) { - substitutionMapping - .setSubstitution_filter(convertToSubstitutionFilterComponent(component.getSubstitutionFilter())); + private void convertSubstitutionMappingFilter(final Component component, final SubstitutionMapping substitutionMapping) { + if (component.getSubstitutionFilter() != null && (component.getSubstitutionFilter().getProperties()).getListToscaDataDefinition() != null) { + substitutionMapping.setSubstitution_filter(convertToSubstitutionFilterComponent(component.getSubstitutionFilter())); } } @@ -430,8 +398,7 @@ public class ToscaExportHandler { } } - private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) - throws SdcResourceNotFoundException { + private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) throws SdcResourceNotFoundException { Map policies = policyExportParser.getPolicies(component); if (policies != null) { topologyTemplate.addPolicies(policies); @@ -442,24 +409,20 @@ public class ToscaExportHandler { return convertMetadata(component, false, null); } - private Map convertMetadata(Component component, boolean isInstance, - ComponentInstance componentInstance) { + private Map convertMetadata(Component component, boolean isInstance, ComponentInstance componentInstance) { Map toscaMetadata = new LinkedHashMap<>(); toscaMetadata.put(convertMetadataKey(JsonPresentationFields.INVARIANT_UUID), component.getInvariantUUID()); toscaMetadata.put(JsonPresentationFields.UUID.getPresentation(), component.getUUID()); toscaMetadata .put(JsonPresentationFields.NAME.getPresentation(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); toscaMetadata.put(JsonPresentationFields.DESCRIPTION.getPresentation(), component.getDescription()); - List categories = component.getCategories(); CategoryDefinition categoryDefinition = categories.get(0); toscaMetadata.put(JsonPresentationFields.CATEGORY.getPresentation(), categoryDefinition.getName()); - if (isInstance) { toscaMetadata.put(JsonPresentationFields.VERSION.getPresentation(), component.getVersion()); toscaMetadata.put(JsonPresentationFields.CUSTOMIZATION_UUID.getPresentation(), componentInstance.getCustomizationUUID()); - if (componentInstance.getSourceModelInvariant() != null - && !componentInstance.getSourceModelInvariant().isEmpty()) { + if (componentInstance.getSourceModelInvariant() != null && !componentInstance.getSourceModelInvariant().isEmpty()) { toscaMetadata.put(JsonPresentationFields.VERSION.getPresentation(), componentInstance.getComponentVersion()); toscaMetadata.put(JsonPresentationFields.CI_SOURCE_MODEL_INVARIANT.getPresentation(), componentInstance.getSourceModelInvariant()); toscaMetadata.put(JsonPresentationFields.CI_SOURCE_MODEL_UUID.getPresentation(), componentInstance.getSourceModelUuid()); @@ -469,17 +432,14 @@ public class ToscaExportHandler { componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue()); } else if (componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) { toscaMetadata.put(JsonPresentationFields.NAME.getPresentation(), - componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceSubstitution - .getDisplayValue()); + componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceSubstitution.getDisplayValue()); } toscaMetadata.put(JsonPresentationFields.DESCRIPTION.getPresentation(), componentInstance.getDescription()); } - } switch (component.getComponentType()) { case RESOURCE: Resource resource = (Resource) component; - if (isInstance && (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution)) { toscaMetadata.put(JsonPresentationFields.TYPE.getPresentation(), componentInstance.getOriginType().getDisplayValue()); @@ -510,13 +470,12 @@ public class ToscaExportHandler { default: log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); } - for (final String key : component.getCategorySpecificMetadata().keySet()) { toscaMetadata.put(key, component.getCategorySpecificMetadata().get(key)); } return toscaMetadata; } - + private String convertMetadataKey(JsonPresentationFields jsonPresentationField) { if (JsonPresentationFields.INVARIANT_UUID.equals(jsonPresentationField)) { return INVARIANT_UUID; @@ -524,23 +483,17 @@ public class ToscaExportHandler { return jsonPresentationField.getPresentation(); } - private Either>, ToscaError> fillImports(Component component, - ToscaTemplate toscaTemplate) { - + private Either>, ToscaError> fillImports(Component component, ToscaTemplate toscaTemplate) { final List>> defaultToscaImportConfig = getDefaultToscaImportConfig(); if (CollectionUtils.isEmpty(defaultToscaImportConfig)) { log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); return Either.right(ToscaError.GENERAL_ERROR); } Map componentCache = new HashMap<>(); - if (!ModelConverter.isAtomicComponent(component)) { final List>> additionalImports = - toscaTemplate.getImports() == null ? new ArrayList<>(defaultToscaImportConfig) - : new ArrayList<>(toscaTemplate.getImports()); - + toscaTemplate.getImports() == null ? new ArrayList<>(defaultToscaImportConfig) : new ArrayList<>(toscaTemplate.getImports()); List> dependecies = new ArrayList<>(); - Map toscaArtifacts = component.getToscaArtifacts(); if (isNotEmpty(toscaArtifacts)) { ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); @@ -549,8 +502,8 @@ public class ToscaExportHandler { Map interfaceFiles = new HashMap<>(); interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); StringBuilder keyNameBuilder = new StringBuilder(); - keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-") - .append(component.getName()).append("-interface"); + keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-").append(component.getName()) + .append("-interface"); importsListMember.put(keyNameBuilder.toString(), interfaceFiles); additionalImports.add(importsListMember); } @@ -571,16 +524,13 @@ public class ToscaExportHandler { return ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports(); } - private void createDependency(final Map componentCache, - final List>> imports, - final List> dependencies, - final ComponentInstance componentInstance) { + private void createDependency(final Map componentCache, final List>> imports, + final List> dependencies, final ComponentInstance componentInstance) { log.debug("createDependency componentCache {}", componentCache); Component componentRI = componentCache.get(componentInstance.getComponentUid()); if (componentRI == null || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) { // all resource must be only once! - final Either resource = toscaOperationFacade - .getToscaFullElement(componentInstance.getComponentUid()); + final Either resource = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); if ((resource.isRight()) && (log.isDebugEnabled())) { log.debug("Failed to fetch resource with id {} for instance {}", componentInstance.getComponentUid(), componentInstance.getUniqueId()); @@ -595,17 +545,16 @@ public class ToscaExportHandler { /** * Sets a componentCache from the given component/resource. */ - private Component setComponentCache(final Map componentCache, - final ComponentInstance componentInstance, - final Component fetchedComponent) { + private Component setComponentCache(final Map componentCache, final ComponentInstance componentInstance, + final Component fetchedComponent) { componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) { final Either sourceService = toscaOperationFacade .getToscaFullElement(componentInstance.getSourceModelUid()); if (sourceService.isRight() && (log.isDebugEnabled())) { - log.debug("Failed to fetch source service with id {} for proxy {}", - componentInstance.getSourceModelUid(), componentInstance.getUniqueId()); + log.debug("Failed to fetch source service with id {} for proxy {}", componentInstance.getSourceModelUid(), + componentInstance.getUniqueId()); } final Component fetchedSource = sourceService.left().value(); componentCache.put(fetchedSource.getUniqueId(), fetchedSource); @@ -617,21 +566,17 @@ public class ToscaExportHandler { /** * Retrieves all derived_from nodes and stores it in a predictable order. */ - private void addDependencies(final List>> imports, - final List> dependencies, + private void addDependencies(final List>> imports, final List> dependencies, final Component fetchedComponent) { final Set componentsList = new LinkedHashSet<>(); if (fetchedComponent instanceof Resource) { log.debug("fetchedComponent is a resource {}", fetchedComponent); - - final Optional> derivedFromMapOfIdToName = getDerivedFromMapOfIdToName(fetchedComponent, - componentsList); + final Optional> derivedFromMapOfIdToName = getDerivedFromMapOfIdToName(fetchedComponent, componentsList); if (derivedFromMapOfIdToName.isPresent() && !derivedFromMapOfIdToName.get().isEmpty()) { derivedFromMapOfIdToName.get().entrySet().forEach(entry -> { log.debug("Started entry.getValue() : {}", entry.getValue()); if (!NATIVE_ROOT.equals(entry.getValue())) { - Either resourcefetched = toscaOperationFacade - .getToscaElement(entry.getKey()); + Either resourcefetched = toscaOperationFacade.getToscaElement(entry.getKey()); if (resourcefetched != null && resourcefetched.isLeft()) { componentsList.add(resourcefetched.left().value()); } @@ -641,15 +586,13 @@ public class ToscaExportHandler { } else { setImports(imports, dependencies, fetchedComponent); } - } } /** * Returns all derived_from nodes found. */ - private Optional> getDerivedFromMapOfIdToName(final Component fetchedComponent, - final Set componentsList) { + private Optional> getDerivedFromMapOfIdToName(final Component fetchedComponent, final Set componentsList) { final Resource parentResource = (Resource) fetchedComponent; Map derivedFromMapOfIdToName = new HashMap<>(); if (CollectionUtils.isNotEmpty(parentResource.getComponentInstances())) { @@ -658,8 +601,7 @@ public class ToscaExportHandler { final Either resourcefetched = toscaOperationFacade .getToscaElement(componentInstance.getComponentUid()); if (resourcefetched != null && resourcefetched.isLeft()) { - final Map derivedWithId = resourcefetched.left().value() - .getDerivedFromMapOfIdToName(); + final Map derivedWithId = resourcefetched.left().value().getDerivedFromMapOfIdToName(); if (MapUtils.isNotEmpty(derivedWithId)) { derivedFromMapOfIdToName.putAll(derivedWithId); } @@ -675,14 +617,12 @@ public class ToscaExportHandler { /** * Creates a resource map and adds it to the import list. */ - private void setImports(final List>> imports, - final List> dependencies, + private void setImports(final List>> imports, final List> dependencies, final Set componentsList) { componentsList.forEach(component -> setImports(imports, dependencies, component)); } - private void setImports(final List>> imports, - final List> dependencies, + private void setImports(final List>> imports, final List> dependencies, final Component component) { final Map toscaArtifacts = component.getToscaArtifacts(); final ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); @@ -695,9 +635,7 @@ public class ToscaExportHandler { keyNameBuilder.append("-"); keyNameBuilder.append(component.getName()); addImports(imports, keyNameBuilder, files); - dependencies - .add(new ImmutableTriple<>(artifactName, artifactDefinition.getEsId(), component)); - + dependencies.add(new ImmutableTriple<>(artifactName, artifactDefinition.getEsId(), component)); if (!ModelConverter.isAtomicComponent(component)) { final Map interfaceFiles = new HashMap<>(); interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName)); @@ -710,8 +648,7 @@ public class ToscaExportHandler { /** * Adds the found resource to the import definition list. */ - private void addImports(final List>> imports, - final StringBuilder keyNameBuilder, + private void addImports(final List>> imports, final StringBuilder keyNameBuilder, final Map files) { final String mapKey = keyNameBuilder.toString(); if (imports.stream().allMatch(stringMapMap -> stringMapMap.get(mapKey) == null)) { @@ -721,50 +658,35 @@ public class ToscaExportHandler { } } - public static String getInterfaceFilename(String artifactName) { - return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; - } - - private Either convertNodeType(Map componentsCache, - Component component, ToscaTemplate toscaNode, + private Either convertNodeType(Map componentsCache, Component component, ToscaTemplate toscaNode, Map nodeTypes) { return convertInterfaceNodeType(componentsCache, component, toscaNode, nodeTypes, false); } - public Either convertInterfaceNodeType(Map componentsCache, - Component component, ToscaTemplate toscaNode, - Map nodeTypes, + public Either convertInterfaceNodeType(Map componentsCache, Component component, + ToscaTemplate toscaNode, Map nodeTypes, boolean isAssociatedComponent) { log.debug("start convert node type for {}", component.getUniqueId()); ToscaNodeType toscaNodeType = createNodeType(component); - - Either, StorageOperationStatus> lifecycleTypeEither = - interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(); + Either, StorageOperationStatus> lifecycleTypeEither = interfaceLifecycleOperation + .getAllInterfaceLifecycleTypes(); if (lifecycleTypeEither.isRight()) { log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value()); return Either.right(ToscaError.GENERAL_ERROR); } - List allGlobalInterfaceTypes = lifecycleTypeEither.left().value() - .values() - .stream() - .map(InterfaceDataDefinition::getType) + List allGlobalInterfaceTypes = lifecycleTypeEither.left().value().values().stream().map(InterfaceDataDefinition::getType) .collect(Collectors.toList()); toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes)); - Either, JanusGraphOperationStatus> 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 mergedProperties = new HashMap<>(); - interfacesOperationsConverter - .addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent); + interfacesOperationsConverter.addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent); addInputsToProperties(dataTypes, inputDef, mergedProperties); - final Map toscaAttributeMap; try { toscaAttributeMap = convertToToscaAttributes(component.getAttributes(), dataTypes); @@ -780,17 +702,15 @@ public class ToscaExportHandler { if (CollectionUtils.isNotEmpty(component.getProperties())) { List properties = component.getProperties(); Map convertedProperties = properties.stream() - .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, component.getInputs())) - .collect(Collectors.toMap(PropertyDataDefinition::getName, - property -> propertyConvertor.convertProperty(dataTypes, property, - PropertyConvertor.PropertyType.PROPERTY))); + .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, component.getInputs())).collect(Collectors + .toMap(PropertyDataDefinition::getName, + property -> propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY))); // merge component properties and inputs properties mergedProperties.putAll(convertedProperties); } if (MapUtils.isNotEmpty(mergedProperties)) { toscaNodeType.setProperties(mergedProperties); } - /* convert private data_types */ List privateDataTypes = component.getDataTypes(); if (CollectionUtils.isNotEmpty(privateDataTypes)) { @@ -1467,32 +1387,27 @@ public class ToscaExportHandler { 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()); + log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}", requirement.getName(), + reqAndRelationshipPair.getRequirement()); return false; } - return ModelConverter.isAtomicComponent(originComponent) || - isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent); + return ModelConverter.isAtomicComponent(originComponent) || isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, + originComponent); } - private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, - RequirementDefinition requirement, String fromInstanceId, + 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()) - || StringUtils.equals(requirement.getOwnerId(), originComponent.getUniqueId())); + return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || ( + isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()) || StringUtils + .equals(requirement.getOwnerId(), originComponent.getUniqueId())); } private boolean isCvfc(Component component) { - return component.getComponentType() == ComponentTypeEnum.RESOURCE && - ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC; + return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC; } - private Either convertCapabilities(Component component, - SubstitutionMapping substitutionMappings, + private Either convertCapabilities(Component component, SubstitutionMapping substitutionMappings, Map componentCache) { - Either result = Either.left(substitutionMappings); Either, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter .convertSubstitutionMappingCapabilities(componentCache, component); @@ -1507,22 +1422,17 @@ public class ToscaExportHandler { return result; } - private Either convertCapabilities(Map componentsCache, - Component component, ToscaNodeType nodeType, + private Either convertCapabilities(Map componentsCache, Component component, ToscaNodeType nodeType, Map dataTypes) { - Map toscaCapabilities = capabilityRequirementConverter - .convertCapabilities(componentsCache, component, - dataTypes); + Map toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component, dataTypes); if (!toscaCapabilities.isEmpty()) { nodeType.setCapabilities(toscaCapabilities); } log.debug("Finish convert Capabilities for node type"); - return Either.left(nodeType); } - private Map convertToNodeTemplateArtifacts( - Map artifacts) { + private Map convertToNodeTemplateArtifacts(Map artifacts) { if (artifacts == null) { return null; } @@ -1541,58 +1451,40 @@ public class ToscaExportHandler { return null; } NodeFilter nodeFilter = new NodeFilter(); - - ListDataDefinition origCapabilities = - inNodeFilter.getCapabilities(); - + ListDataDefinition origCapabilities = inNodeFilter.getCapabilities(); ListDataDefinition origProperties = inNodeFilter.getProperties(); - List> capabilitiesCopy = new ArrayList<>(); List>> propertiesCopy = new ArrayList<>(); - copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy); copyNodeFilterProperties(origProperties, propertiesCopy); - if (CollectionUtils.isNotEmpty(capabilitiesCopy)) { nodeFilter.setCapabilities(capabilitiesCopy); } - if (CollectionUtils.isNotEmpty(propertiesCopy)) { nodeFilter.setProperties(propertiesCopy); } - nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id())); - nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class); - return nodeFilter; } - private NodeFilter convertToSubstitutionFilterComponent( - final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) { - + private NodeFilter convertToSubstitutionFilterComponent(final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) { if (substitutionFilterDataDefinition == null) { return null; } NodeFilter nodeFilter = new NodeFilter(); - - ListDataDefinition origProperties = - substitutionFilterDataDefinition.getProperties(); + ListDataDefinition origProperties = substitutionFilterDataDefinition.getProperties(); List>> propertiesCopy = new ArrayList<>(); - copySubstitutionFilterProperties(origProperties, propertiesCopy); - if (CollectionUtils.isNotEmpty(propertiesCopy)) { nodeFilter.setProperties(propertiesCopy); } nodeFilter.setTosca_id(cloneToscaId(substitutionFilterDataDefinition.getTosca_id())); - return (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class); } private Object cloneToscaId(Object toscaId) { - return Objects.isNull(toscaId) ? null - : cloneObjectFromYml(toscaId, toscaId.getClass()); + return Objects.isNull(toscaId) ? null : cloneObjectFromYml(toscaId, toscaId.getClass()); } private Object cloneObjectFromYml(Object objToClone, Class classOfObj) { @@ -1600,11 +1492,10 @@ public class ToscaExportHandler { return yamlUtil.yamlToObject(objectAsYml, classOfObj); } - private void copyNodeFilterCapabilitiesTemplate( - ListDataDefinition origCapabilities, - List> capabilitiesCopy) { - if (origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null || - origCapabilities.getListToscaDataDefinition().isEmpty()) { + private void copyNodeFilterCapabilitiesTemplate(ListDataDefinition origCapabilities, + List> capabilitiesCopy) { + if (origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null || origCapabilities.getListToscaDataDefinition() + .isEmpty()) { return; } for (RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) { @@ -1618,16 +1509,13 @@ public class ToscaExportHandler { } } - private void copyNodeFilterProperties( - ListDataDefinition origProperties, - List>> propertiesCopy) { - if (origProperties == null || origProperties.getListToscaDataDefinition() == null || - origProperties.isEmpty()) { + private void copyNodeFilterProperties(ListDataDefinition origProperties, + List>> propertiesCopy) { + if (origProperties == null || origProperties.getListToscaDataDefinition() == null || origProperties.isEmpty()) { return; } Map> propertyMapCopy = new HashMap<>(); - for (RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties - .getListToscaDataDefinition()) { + for (RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) { for (String propertyInfoEntry : propertyDataDefinition.getConstraints()) { Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class); String propertyName = propertyDataDefinition.getName(); @@ -1644,23 +1532,18 @@ public class ToscaExportHandler { } } } - propertyMapCopy.entrySet().stream().forEach(entry -> - addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry)); + propertyMapCopy.entrySet().stream().forEach(entry -> addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry)); } - private void copySubstitutionFilterProperties( - final ListDataDefinition origProperties, - final List>> propertiesCopy) { - if (origProperties == null || origProperties.getListToscaDataDefinition() == null || - origProperties.isEmpty()) { + private void copySubstitutionFilterProperties(final ListDataDefinition origProperties, + final List>> propertiesCopy) { + if (origProperties == null || origProperties.getListToscaDataDefinition() == null || origProperties.isEmpty()) { return; } final Map> propertyMapCopy = new HashMap<>(); - for (final RequirementSubstitutionFilterPropertyDataDefinition propertyDataDefinition : origProperties - .getListToscaDataDefinition()) { + for (final RequirementSubstitutionFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) { for (final String propertyInfoEntry : propertyDataDefinition.getConstraints()) { - final Map> propertyValObj = new YamlUtil() - .yamlToObject(propertyInfoEntry, Map.class); + final Map> propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class); final String propertyName = propertyDataDefinition.getName(); if (propertyMapCopy.containsKey(propertyName)) { addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName)); @@ -1675,8 +1558,7 @@ public class ToscaExportHandler { } } } - propertyMapCopy.entrySet().forEach(entry -> - addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry)); + propertyMapCopy.entrySet().forEach(entry -> addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry)); } private void addPropertyConstraintValueToList(String propertyName, Map> propertyValObj, List propsList) { @@ -1687,84 +1569,77 @@ public class ToscaExportHandler { } } - private void addCalculatedConstraintsIntoPropertiesList(List>> propertiesCopy, - Entry> entry) { + private void addCalculatedConstraintsIntoPropertiesList(List>> propertiesCopy, Entry> entry) { Map> tempMap = new HashMap<>(); tempMap.put(entry.getKey(), entry.getValue()); propertiesCopy.add(tempMap); } - private static class CustomRepresenter extends Representer { - - CustomRepresenter() { - super(); - this.representers.put(ToscaPropertyAssignment.class, new RepresentToscaPropertyAssignment()); - this.representers.put(ToscaAttribute.class, new RepresentToscaAttribute()); - // null representer is exceptional and it is stored as an instance - // variable. - this.nullRepresenter = new RepresentNull(); - + private Map buildSubstitutionMappingPropertyMapping(final Component component) { + if (component == null || CollectionUtils.isEmpty(component.getInputs())) { + return Collections.emptyMap(); } + return component.getInputs().stream().filter(input -> input.isMappedToComponentProperty()).map(PropertyDataDefinition::getName) + .collect(Collectors.toMap(inputName -> inputName, inputName -> new String[]{inputName}, (inputName1, inputName2) -> inputName1)); + } - private class RepresentToscaAttribute implements Represent { + private Map buildSubstitutionMappingAttributesMapping(final Component component) { + if (component == null || CollectionUtils.isEmpty(component.getOutputs())) { + return Collections.emptyMap(); + } + return component.getOutputs().stream().map(AttributeDataDefinition::getName) + .collect(Collectors.toMap(outputName -> outputName, outputName -> new String[]{outputName}, (outputName1, outputName2) -> outputName1)); + } - @Override - public Node representData(Object data) { - final ToscaAttribute toscaAttribute = (ToscaAttribute) data; - return represent(toscaAttribute.asToscaMap()); - } + Optional> getProxyNodeTypeProperties(Component proxyComponent, Map dataTypes) { + if (Objects.isNull(proxyComponent)) { + return Optional.empty(); + } + Map proxyProperties = new HashMap<>(); + addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyProperties); + if (CollectionUtils.isNotEmpty(proxyComponent.getProperties())) { + proxyProperties.putAll(proxyComponent.getProperties().stream() + .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, proxyComponent.getInputs())).collect(Collectors + .toMap(PropertyDataDefinition::getName, + property -> propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY)))); } + return MapUtils.isNotEmpty(proxyProperties) ? Optional.of(proxyProperties) : Optional.empty(); + } - private class RepresentToscaPropertyAssignment implements Represent { + void addInputsToProperties(Map dataTypes, List componentInputs, + Map mergedProperties) { + if (CollectionUtils.isEmpty(componentInputs)) { + return; + } + for (InputDefinition input : componentInputs) { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT); + mergedProperties.put(input.getName(), property); + } + } - public Node representData(Object data) { - final ToscaPropertyAssignment toscaOperationAssignment = (ToscaPropertyAssignment) data; - if (toscaOperationAssignment.getValue() instanceof String) { - final String stringValue = (String) toscaOperationAssignment.getValue(); - if (isPropertyOrAttributeFunction(stringValue)) { - return representGetAttribute(stringValue); - } + Optional> getProxyNodeTypeInterfaces(Component proxyComponent, Map dataTypes) { + if (Objects.isNull(proxyComponent) || MapUtils.isEmpty(proxyComponent.getInterfaces())) { + return Optional.empty(); + } + Map proxyComponentInterfaces = proxyComponent.getInterfaces(); + //Unset artifact path for operation implementation for proxy node types as for operations with artifacts it is - return representScalar(Tag.STR, stringValue); - } - return represent(null); - } + // always available in the proxy node template + removeOperationImplementationForProxyNodeType(proxyComponentInterfaces); + return Optional + .ofNullable(interfacesOperationsConverter.getInterfacesMap(proxyComponent, null, proxyComponentInterfaces, dataTypes, false, false)); + } - public Node representGetAttribute(final String getAttributeFunction) { - return represent(new Yaml().load(getAttributeFunction)); - } + private static class CustomRepresenter extends Representer { - public boolean isPropertyOrAttributeFunction(final String value) { - try { - final Yaml yaml = new Yaml(); - final Object yamlObj = yaml.load(value); - if (!(yamlObj instanceof Map)) { - return false; - } - final Map getAttributeMap = (Map) yamlObj; - if (getAttributeMap.size() != 1) { - return false; - } - final List functionList = Arrays - .asList(GET_ATTRIBUTE.getFunctionName(), GET_INPUT.getFunctionName(), - GET_PROPERTY.getFunctionName()); - final Optional function = getAttributeMap.keySet().stream() - .filter(key -> functionList.stream().anyMatch(function1 -> function1.equals(key))).findFirst(); + CustomRepresenter() { + super(); + this.representers.put(ToscaPropertyAssignment.class, new RepresentToscaPropertyAssignment()); + this.representers.put(ToscaAttribute.class, new RepresentToscaAttribute()); + // null representer is exceptional and it is stored as an instance - if (function.isEmpty()) { - return false; - } - final String functionName = function.get(); - final Object getAttributeValueObj = getAttributeMap.get(functionName); - if (GET_INPUT.getFunctionName().equals(functionName)) { - return validateGetInputValue(getAttributeValueObj); - } else { - return validateGetPropertyOrAttributeValue(getAttributeValueObj); - } - } catch (final Exception ignored) { - return false; - } - } + // variable. + this.nullRepresenter = new RepresentNull(); } public boolean validateGetInputValue(final Object valueObj) { @@ -1774,7 +1649,6 @@ public class ToscaExportHandler { if (valueObj instanceof List) { return ((List) valueObj).size() > 1; } - return true; } @@ -1782,13 +1656,11 @@ public class ToscaExportHandler { if (valueObj instanceof List) { return ((List) valueObj).size() > 1; } - return false; } @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, - Tag customTag) { + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { if (propertyValue == null) { return null; } @@ -1799,27 +1671,21 @@ public class ToscaExportHandler { if (javaBean instanceof ToscaRelationshipTemplate && "name".equals(property.getName())) { return null; } - removeDefaultP(propertyValue); NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); - if (javaBean instanceof ToscaTopolgyTemplate && "relationshipTemplates".equals(property.getName())) { return new NodeTuple(representData("relationship_templates"), defaultNode.getValueNode()); } - - return "_defaultp_".equals(property.getName()) - ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; + return "_defaultp_".equals(property.getName()) ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; } private void removeDefaultP(final Object propertyValue) { if (propertyValue instanceof Map) { final Map mapPropertyValue = ((Map) propertyValue); - final Iterator iter = mapPropertyValue.entrySet().iterator(); Object defaultValue = null; while (iter.hasNext()) { final Map.Entry entry = iter.next(); - if ("_defaultp_".equals(entry.getKey())) { defaultValue = entry.getValue(); iter.remove(); @@ -1839,110 +1705,83 @@ public class ToscaExportHandler { if (!classTags.containsKey(javaBean.getClass())) { addClassTag(javaBean.getClass(), Tag.MAP); } - return super.representJavaBean(properties, javaBean); } - private class RepresentNull implements Represent { + private class RepresentToscaAttribute implements Represent { @Override public Node representData(Object data) { - // possible values are here http://yaml.org/type/null.html - return representScalar(Tag.NULL, ""); + final ToscaAttribute toscaAttribute = (ToscaAttribute) data; + return represent(toscaAttribute.asToscaMap()); } } - } - private static class UnsortedPropertyUtils extends PropertyUtils { + private class RepresentToscaPropertyAssignment implements Represent { - @Override - protected Set createPropertySet(Class type, BeanAccess bAccess) { - Collection fields = getPropertiesMap(type, BeanAccess.FIELD).values(); - return new LinkedHashSet<>(fields); - } - } + public Node representData(Object data) { + final ToscaPropertyAssignment toscaOperationAssignment = (ToscaPropertyAssignment) data; + if (toscaOperationAssignment.getValue() instanceof String) { + final String stringValue = (String) toscaOperationAssignment.getValue(); + if (isPropertyOrAttributeFunction(stringValue)) { + return representGetAttribute(stringValue); + } + return representScalar(Tag.STR, stringValue); + } + return represent(null); + } - private Map buildSubstitutionMappingPropertyMapping(final Component component) { - if (component == null || CollectionUtils.isEmpty(component.getInputs())) { - return Collections.emptyMap(); - } - return component.getInputs().stream().filter(input -> input.isMappedToComponentProperty()) - .map(PropertyDataDefinition::getName) - .collect( - Collectors.toMap( - inputName -> inputName, - inputName -> new String[]{inputName}, - (inputName1, inputName2) -> inputName1) - ); - } + public Node representGetAttribute(final String getAttributeFunction) { + return represent(new Yaml().load(getAttributeFunction)); + } - private Map buildSubstitutionMappingAttributesMapping(final Component component) { - if (component == null || CollectionUtils.isEmpty(component.getOutputs())) { - return Collections.emptyMap(); + public boolean isPropertyOrAttributeFunction(final String value) { + try { + final Yaml yaml = new Yaml(); + final Object yamlObj = yaml.load(value); + if (!(yamlObj instanceof Map)) { + return false; + } + final Map getAttributeMap = (Map) yamlObj; + if (getAttributeMap.size() != 1) { + return false; + } + final List functionList = Arrays + .asList(GET_ATTRIBUTE.getFunctionName(), GET_INPUT.getFunctionName(), GET_PROPERTY.getFunctionName()); + final Optional function = getAttributeMap.keySet().stream() + .filter(key -> functionList.stream().anyMatch(function1 -> function1.equals(key))).findFirst(); + if (function.isEmpty()) { + return false; + } + final String functionName = function.get(); + final Object getAttributeValueObj = getAttributeMap.get(functionName); + if (GET_INPUT.getFunctionName().equals(functionName)) { + return validateGetInputValue(getAttributeValueObj); + } else { + return validateGetPropertyOrAttributeValue(getAttributeValueObj); + } + } catch (final Exception ignored) { + return false; + } + } } - return component.getOutputs().stream() - .map(AttributeDataDefinition::getName) - .collect( - Collectors.toMap( - outputName -> outputName, - outputName -> new String[]{outputName}, - (outputName1, outputName2) -> outputName1) - ); - } - Optional> getProxyNodeTypeProperties(Component proxyComponent, - Map - dataTypes) { - if (Objects.isNull(proxyComponent)) { - return Optional.empty(); - } - Map proxyProperties = new HashMap<>(); - addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyProperties); - if (CollectionUtils.isNotEmpty(proxyComponent.getProperties())) { - proxyProperties.putAll(proxyComponent.getProperties().stream() - .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, - proxyComponent.getInputs())) - .collect(Collectors.toMap(PropertyDataDefinition::getName, - property -> propertyConvertor.convertProperty(dataTypes, property, - PropertyConvertor.PropertyType.PROPERTY)))); - } - return MapUtils.isNotEmpty(proxyProperties) ? Optional.of(proxyProperties) : Optional.empty(); - } + private class RepresentNull implements Represent { - void addInputsToProperties(Map dataTypes, - List componentInputs, - Map mergedProperties) { - if (CollectionUtils.isEmpty(componentInputs)) { - return; - } - for (InputDefinition input : componentInputs) { - ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, - PropertyConvertor.PropertyType.INPUT); - mergedProperties.put(input.getName(), property); + @Override + public Node representData(Object data) { + // possible values are here http://yaml.org/type/null.html + return representScalar(Tag.NULL, ""); + } } } - Optional> getProxyNodeTypeInterfaces(Component proxyComponent, - Map dataTypes) { - if (Objects.isNull(proxyComponent) || MapUtils.isEmpty(proxyComponent.getInterfaces())) { - return Optional.empty(); - } - Map proxyComponentInterfaces = proxyComponent.getInterfaces(); - //Unset artifact path for operation implementation for proxy node types as for operations with artifacts it is - // always available in the proxy node template - removeOperationImplementationForProxyNodeType(proxyComponentInterfaces); - return Optional.ofNullable(interfacesOperationsConverter - .getInterfacesMap(proxyComponent, null, proxyComponentInterfaces, dataTypes, - false, false)); - } + private static class UnsortedPropertyUtils extends PropertyUtils { - private static void removeOperationImplementationForProxyNodeType( - Map proxyComponentInterfaces) { - if (MapUtils.isEmpty(proxyComponentInterfaces)) { - return; + @Override + protected Set createPropertySet(Class type, BeanAccess bAccess) { + Collection fields = getPropertiesMap(type, BeanAccess.FIELD).values(); + return new LinkedHashSet<>(fields); } - proxyComponentInterfaces.values().stream().map(InterfaceDataDefinition::getOperations) - .filter(MapUtils::isNotEmpty) - .forEach(operations -> operations.values().forEach(operation -> operation.setImplementation(null))); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportRelationshipTemplatesHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportRelationshipTemplatesHandler.java index c706063d75..4ee8ff0855 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportRelationshipTemplatesHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportRelationshipTemplatesHandler.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; import static org.apache.commons.collections.CollectionUtils.isEmpty; @@ -47,7 +46,6 @@ public class ToscaExportRelationshipTemplatesHandler { if (MapUtils.isEmpty(nodeTemplateMap)) { return Collections.emptyMap(); } - final Map relationshipTemplates = new HashMap<>(); for (final Entry nodeEntry : nodeTemplateMap.entrySet()) { final ToscaNodeTemplate nodeTemplate = nodeEntry.getValue(); @@ -56,28 +54,22 @@ public class ToscaExportRelationshipTemplatesHandler { } final AtomicInteger relationshipTemplateCount = new AtomicInteger(1); for (final Map requirementMap : nodeTemplate.getRequirements()) { - requirementMap.entrySet().stream() - .filter(entry -> entry.getValue().isRelationshipComplexNotation()) - .forEach(requirementEntry -> { - final ToscaTemplateRequirement requirement = requirementEntry.getValue(); - final ToscaRelationship relationship = requirement.getRelationshipAsComplexType(); - final ToscaRelationshipTemplate relationshipTemplate = new ToscaRelationshipTemplate(); - relationshipTemplate.setType(relationship.getType()); - relationshipTemplate.setInterfaces(relationship.getInterfaces()); - final String relationshipName = String.format("%s.%s", - ToscaRelationshipTemplate - .createRelationshipName(nodeEntry.getKey(), requirementEntry.getKey()), + requirementMap.entrySet().stream().filter(entry -> entry.getValue().isRelationshipComplexNotation()).forEach(requirementEntry -> { + final ToscaTemplateRequirement requirement = requirementEntry.getValue(); + final ToscaRelationship relationship = requirement.getRelationshipAsComplexType(); + final ToscaRelationshipTemplate relationshipTemplate = new ToscaRelationshipTemplate(); + relationshipTemplate.setType(relationship.getType()); + relationshipTemplate.setInterfaces(relationship.getInterfaces()); + final String relationshipName = String + .format("%s.%s", ToscaRelationshipTemplate.createRelationshipName(nodeEntry.getKey(), requirementEntry.getKey()), relationshipTemplateCount); - - requirement.setRelationship(relationshipName); - relationshipTemplate.setName(relationshipName); - relationshipTemplates.put(relationshipName, relationshipTemplate); - relationshipTemplateCount.incrementAndGet(); - }); + requirement.setRelationship(relationshipName); + relationshipTemplate.setName(relationshipName); + relationshipTemplates.put(relationshipName, relationshipTemplate); + relationshipTemplateCount.incrementAndGet(); + }); } } - return relationshipTemplates; } - } 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 1ca95576a8..07463f83e4 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 @@ -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. @@ -17,22 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; import io.vavr.control.Option; +import java.util.List; import lombok.Getter; import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.model.Component; - -import java.util.List; import org.openecomp.sdc.be.tosca.model.ToscaTemplate; public class ToscaRepresentation { @Getter private final byte[] mainYaml; - @Getter private final Option>> dependencies; 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 38e60617c4..0f133957ca 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 @@ -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. @@ -17,33 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; -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.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; + public class ToscaUtils { - private ToscaUtils() {} + private ToscaUtils() { + } public static boolean isNotComplexVfc(Component component) { if (ComponentTypeEnum.RESOURCE == component.getComponentType()) { - ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (ResourceTypeEnum.CVFC == resourceType ) { + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()) + .getResourceType(); + if (ResourceTypeEnum.CVFC == resourceType) { return false; } - if (component.getComponentMetadataDefinition()!=null && component.getComponentMetadataDefinition().getMetadataDataDefinition()!=null - && component.getComponentMetadataDefinition().getMetadataDataDefinition().getDescription()!=null){ - if(component.getComponentMetadataDefinition().getMetadataDataDefinition().getDescription().equalsIgnoreCase("Nested VF in service")){ + if (component.getComponentMetadataDefinition() != null && component.getComponentMetadataDefinition().getMetadataDataDefinition() != null + && component.getComponentMetadataDefinition().getMetadataDataDefinition().getDescription() != null) { + if (component.getComponentMetadataDefinition().getMetadataDataDefinition().getDescription() + .equalsIgnoreCase("Nested VF in service")) { return false; } } @@ -54,9 +56,7 @@ public class ToscaUtils { public static Map objectToMap(Object objectToConvert, Class clazz) throws 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)); @@ -79,13 +79,13 @@ public class ToscaUtils { private String owner = ""; SubstitutionEntry(String fullName, String sourceName, String owner) { - if(fullName != null) { + if (fullName != null) { this.fullName = fullName; } - if(sourceName != null) { + if (sourceName != null) { this.sourceName = sourceName; } - if(owner != null) { + if (owner != null) { this.owner = owner; } } @@ -114,5 +114,4 @@ public class ToscaUtils { this.owner = owner; } } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ZipWriter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ZipWriter.java index 916895fff4..55ae7286bb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ZipWriter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ZipWriter.java @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca; -import fj.data.Either; import io.vavr.control.Try; import java.util.function.Function; import java.util.zip.ZipEntry; @@ -31,11 +29,25 @@ import java.util.zip.ZipOutputStream; */ public interface ZipWriter { + /** + * Builds a ZipWriter that outputs the data on a {@link java.util.zip.ZipOutputStream} + * + * @param zos the target {@link java.util.zip.ZipOutputStream} + */ + static ZipWriter live(ZipOutputStream zos) { + return (entryName, payload) -> Try.of(() -> { + zos.putNextEntry(new ZipEntry(entryName)); + zos.write(payload); + // We can return null as a Void is expected; + return null; + }); + } + /** * Writes an entry provided with its name and its payload * * @param entryName The entry's name to use in the zip file - * @param payload The payload to write for this entry + * @param payload The payload to write for this entry */ Try write(String entryName, byte[] payload); @@ -43,7 +55,7 @@ public interface ZipWriter { * Writes an entry provided with its name and its payload * * @param entryName The entry's name to use in the zip file - * @param payload The payload to write for this entry + * @param payload The payload to write for this entry */ default Try write(String entryName, String payload) { return write(entryName, payload.getBytes()); @@ -61,18 +73,4 @@ public interface ZipWriter { default Function> write(String entryName) { return payload -> write(entryName, payload); } - - /** - * Builds a ZipWriter that outputs the data on a {@link java.util.zip.ZipOutputStream} - * @param zos the target {@link java.util.zip.ZipOutputStream} - */ - static ZipWriter live(ZipOutputStream zos) { - return (entryName, payload) -> Try.of(() -> { - zos.putNextEntry(new ZipEntry(entryName)); - zos.write(payload); - // We can return null as a Void is expected; - return null; - }); - } } - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/builder/ToscaRelationshipBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/builder/ToscaRelationshipBuilder.java index c3c9607664..1dec236fff 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/builder/ToscaRelationshipBuilder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/builder/ToscaRelationshipBuilder.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.builder; import java.util.HashMap; @@ -56,7 +55,6 @@ public class ToscaRelationshipBuilder { toscaProperty.setValue(propertyAssignmentUi.getValue()); inputMap.put(propertyAssignmentUi.getName(), toscaProperty); }); - toscaOperationAssignment.setInputs(inputMap); } operationDefinitionMap.put(operationUi.getOperationType(), toscaOperationAssignment); @@ -67,5 +65,4 @@ public class ToscaRelationshipBuilder { toscaRelationship.setInterfaces(interfaceMap); return toscaRelationship; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/exception/ToscaConversionException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/exception/ToscaConversionException.java index 2d37a35a96..80a943fd5d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/exception/ToscaConversionException.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/exception/ToscaConversionException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.exception; public class ToscaConversionException extends Exception { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/CapabilityFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/CapabilityFilter.java index 0197c3dabe..579cfc5361 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/CapabilityFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/CapabilityFilter.java @@ -13,18 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.tosca.model; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.commons.collections.CollectionUtils; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - @Getter @Setter @ToString @@ -33,7 +31,7 @@ public class CapabilityFilter { private List>> properties; public void addProperty(Map> property) { - if(CollectionUtils.isEmpty(properties)) { + if (CollectionUtils.isEmpty(properties)) { this.properties = new ArrayList<>(); } this.properties.add(property); 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 1bb865f562..e24316ca02 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; public interface IToscaMetadata { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/NodeFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/NodeFilter.java index f5511edd1b..6cad788a1e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/NodeFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/NodeFilter.java @@ -23,7 +23,8 @@ import lombok.Setter; @Getter @Setter public class NodeFilter { + private Object tosca_id; private List>> properties; private List> capabilities; -} \ No newline at end of file +} 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 7b70a0b5f4..9e3380fbb3 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.Map; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAnnotation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAnnotation.java index 455e1bdc5f..5aee23ddbb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAnnotation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAnnotation.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. @@ -17,26 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.HashMap; import java.util.Map; public class ToscaAnnotation { - private String type; - - private Map properties ; - public void setDescription(String description) { - this.description = description; - } + private String type; + private Map properties; + private String description; public String getDescription() { return description; } - private String description; + public void setDescription(String description) { + this.description = description; + } public String getType() { return type; @@ -45,23 +43,19 @@ public class ToscaAnnotation { public void setType(String type) { this.type = type; } - - public void addProperty(String name, Object property){ - if ( properties == null ){ + + public void addProperty(String name, Object property) { + if (properties == null) { properties = new HashMap<>(); } properties.put(name, property); } - public void setProperties(Map properties) { - this.properties = properties; - } - public Map getProperties() { return properties; } - - - + public void setProperties(Map properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAttribute.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAttribute.java index ea56e60a17..769f32c85e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAttribute.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAttribute.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.LinkedHashMap; @@ -86,8 +85,6 @@ public class ToscaAttribute { if (getStatus() != null) { toscaAttributeAsMap.put(ToscaTagNamesEnum.STATUS.getElementName(), getStatus()); } - return toscaAttributeAsMap; } - } 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 d26fd0447c..8a748eddfb 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; @@ -27,13 +26,13 @@ public class ToscaCapability { private String type; private String description; - private List occurrences; - private List valid_source_types; - private Map properties; + public ToscaCapability() { + } + public List getValid_source_types() { return valid_source_types; } @@ -42,9 +41,6 @@ public class ToscaCapability { this.valid_source_types = valid_source_types; } - public ToscaCapability() { - } - public String getType() { return type; } @@ -76,5 +72,4 @@ public class ToscaCapability { public void setProperties(Map properties) { this.properties = properties; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaDataType.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaDataType.java index 8a4ec7c301..a84ef02089 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaDataType.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaDataType.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.Map; 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 605d41e847..c7763e6dc8 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 @@ -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. @@ -17,36 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; import java.util.Map; public class ToscaGroupTemplate { + private String type; private List members; private IToscaMetadata metadata; private Map properties; private Map capabilities; - - public ToscaGroupTemplate(String type, List members, IToscaMetadata metadata, Map properties, Map capabilities) { - this.type = type; - this.members = members; - this.metadata = metadata; - this.properties = properties; - this.capabilities = capabilities; - } - + + public ToscaGroupTemplate(String type, List members, IToscaMetadata metadata, Map properties, + Map capabilities) { + this.type = type; + this.members = members; + this.metadata = metadata; + this.properties = properties; + this.capabilities = capabilities; + } + public ToscaGroupTemplate(String type, IToscaMetadata metadata, Map properties) { - this.type = type; - this.metadata = metadata; - this.properties = properties; - } - - + this.type = type; + this.metadata = metadata; + this.properties = properties; + } - public String getType() { + public String getType() { return type; } @@ -77,13 +76,12 @@ public class ToscaGroupTemplate { public void setProperties(Map properties) { this.properties = properties; } - - public Map getCapabilities() { - return capabilities; - } - public void setCapabilities(Map capabilities) { - this.capabilities = capabilities; - } + public Map getCapabilities() { + return capabilities; + } + public void setCapabilities(Map capabilities) { + this.capabilities = capabilities; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInput.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInput.java index c4eba4fe50..a06f67c005 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInput.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInput.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. @@ -17,21 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.HashMap; import java.util.Map; public class ToscaInput extends ToscaProperty { - private Map annotations; + + private Map annotations; //copy constructor - public ToscaInput(ToscaProperty toscaProperty){ + public ToscaInput(ToscaProperty toscaProperty) { super(toscaProperty); } - public Map getAnnotations() { return annotations; } @@ -39,12 +38,11 @@ public class ToscaInput extends ToscaProperty { public void setAnnotations(Map annotations) { this.annotations = annotations; } - public void addAnnotation(String name, ToscaAnnotation annotaion){ - if ( annotations == null ){ + + public void addAnnotation(String name, ToscaAnnotation annotaion) { + if (annotations == null) { annotations = new HashMap<>(); } annotations.put(name, annotaion); - - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceDefinition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceDefinition.java index 2f4a3d8ac1..01839964c3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceDefinition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceDefinition.java @@ -30,6 +30,4 @@ public class ToscaInterfaceDefinition { private String type; private Map operations; private Map inputs; - } - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceNodeType.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceNodeType.java index 89e0b07cae..d76c2d2fe0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceNodeType.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceNodeType.java @@ -22,54 +22,50 @@ import java.util.Objects; * @author KATYR * @since March 26, 2018 */ - public class ToscaInterfaceNodeType { - private String derived_from; - private String description; - private Map operations; - - - public String getDerived_from() { - return derived_from; - } + private String derived_from; + private String description; + private Map operations; - public void setDerived_from(String derived_from) { - this.derived_from = derived_from; - } - - public String getDescription() { - return description; - } + public String getDerived_from() { + return derived_from; + } - public void setDescription(String description) { - this.description = description; - } + public void setDerived_from(String derived_from) { + this.derived_from = derived_from; + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + public String getDescription() { + return description; } - if (o == null || getClass() != o.getClass()) { - return false; + + public void setDescription(String description) { + this.description = description; } - ToscaInterfaceNodeType that = (ToscaInterfaceNodeType) o; - return Objects.equals(derived_from, that.derived_from) && - Objects.equals(description, that.description); - } - @Override - public int hashCode() { + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ToscaInterfaceNodeType that = (ToscaInterfaceNodeType) o; + return Objects.equals(derived_from, that.derived_from) && Objects.equals(description, that.description); + } - return Objects.hash(derived_from, description); - } + @Override + public int hashCode() { + return Objects.hash(derived_from, description); + } - public Map getOperations() { - return operations; - } + public Map getOperations() { + return operations; + } - public void setOperations(Map operations) { - this.operations = operations; - } + public void setOperations(Map operations) { + this.operations = operations; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaLifecycleOperationDefinition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaLifecycleOperationDefinition.java index f801ac0264..f35cab2795 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaLifecycleOperationDefinition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaLifecycleOperationDefinition.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.tosca.model; import java.util.Map; @@ -23,14 +22,12 @@ import java.util.Objects; * @author KATYR * @since March 26, 2018 */ - public class ToscaLifecycleOperationDefinition { private String description; private String implementation; private Map inputs; - public String getImplementation() { return implementation; } @@ -47,7 +44,6 @@ public class ToscaLifecycleOperationDefinition { this.inputs = inputs; } - @Override public boolean equals(Object o) { if (this == o) { @@ -62,7 +58,6 @@ public class ToscaLifecycleOperationDefinition { @Override public int hashCode() { - return Objects.hash(implementation, inputs); } 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 f496994ac3..97dab3649e 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 @@ -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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; public class ToscaMetadata implements IToscaMetadata { + private String invariantUUID; private String UUID; private String customizationUUID; @@ -45,7 +45,6 @@ public class ToscaMetadata implements IToscaMetadata { private String sourceModelUuid; private String serviceFunction; - public String getName() { return name; } @@ -141,6 +140,10 @@ public class ToscaMetadata implements IToscaMetadata { return serviceRole; } + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + public String getServiceFunction() { return serviceFunction; } @@ -149,16 +152,12 @@ public class ToscaMetadata implements IToscaMetadata { this.serviceFunction = serviceFunction; } - public void setInstantiationType(String instantiationType) { - this.instantiationType = instantiationType; - } - public String getInstantiationType() { return instantiationType; } - public void setServiceRole(String serviceRole) { - this.serviceRole = serviceRole; + public void setInstantiationType(String instantiationType) { + this.instantiationType = instantiationType; } public Boolean isEcompGeneratedNaming() { @@ -166,7 +165,7 @@ public class ToscaMetadata implements IToscaMetadata { } public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { - this.ecompGeneratedNaming = ecompGeneratedNaming == null ? null : ecompGeneratedNaming.toString(); + this.ecompGeneratedNaming = ecompGeneratedNaming == null ? null : ecompGeneratedNaming.toString(); } public String isNamingPolicy() { @@ -182,7 +181,7 @@ public class ToscaMetadata implements IToscaMetadata { } public void setServiceEcompNaming(Boolean serviceEcompNaming) { - this.serviceEcompNaming = serviceEcompNaming == null ? null : serviceEcompNaming.toString(); + this.serviceEcompNaming = serviceEcompNaming == null ? null : serviceEcompNaming.toString(); } public String getVersion() { 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 50a8f3da3b..e65d9a2425 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 @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - @Getter @Setter @NoArgsConstructor @@ -54,7 +52,6 @@ public class ToscaNodeTemplate { if (MapUtils.isEmpty(this.interfaces)) { this.interfaces = new HashMap<>(); } - this.interfaces.put(interfaceName, interfaceDataDefinition); } } 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 c43486fab8..cc3c57c8ef 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; @@ -34,12 +33,9 @@ public class ToscaNodeType { private ToscaMetadata metadata; private String derived_from; private String description; - private Map properties; private Map interfaces; private Map capabilities; - private List> requirements; private Map attributes; - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOperationAssignment.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOperationAssignment.java index 2aba85027e..d7f918de53 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOperationAssignment.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOperationAssignment.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.Map; @@ -30,5 +29,4 @@ public class ToscaOperationAssignment { private String description; private String implementation; private Map inputs; - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOutput.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOutput.java index 826c7fcd8d..90e2374adc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOutput.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOutput.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; public class ToscaOutput extends ToscaProperty { @@ -28,5 +27,4 @@ public class ToscaOutput extends ToscaProperty { this.setDescription(toscaAttribute.getStatus()); this.setValue(toscaAttribute.getValue()); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPolicyTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPolicyTemplate.java index 5d8f200bbe..18f2b7f488 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPolicyTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPolicyTemplate.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. @@ -17,26 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; import java.util.Map; public class ToscaPolicyTemplate { - private String type; + + private String type; private IToscaMetadata metadata; private Map properties; private List targets; - + public ToscaPolicyTemplate(String type, IToscaMetadata metadata, Map properties, List targets) { - this.type = type; - this.metadata = metadata; - this.properties = properties; - this.targets = targets; - } + this.type = type; + this.metadata = metadata; + this.properties = properties; + this.targets = targets; + } - public String getType() { + public String getType() { return type; } @@ -60,14 +60,11 @@ public class ToscaPolicyTemplate { this.properties = properties; } - public List getTargets() { - return targets; - } + public List getTargets() { + return targets; + } - public void setTargets(List targets) { - this.targets = targets; - } - - - + public void setTargets(List targets) { + this.targets = targets; + } } 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 fb5c544511..f6e74c9d1c 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; @@ -73,5 +72,4 @@ public class ToscaProperty { public void setDefaultp(Object defaultp) { this._defaultp_ = defaultp; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyAssignment.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyAssignment.java index f42b655cbf..44eb209d95 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyAssignment.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyAssignment.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import lombok.Getter; @@ -27,5 +26,4 @@ import lombok.Setter; public class ToscaPropertyAssignment { private Object value; - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraint.java index 2faceb3bb1..ab1137342d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraint.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraint.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType; @@ -27,5 +26,4 @@ import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType; public interface ToscaPropertyConstraint { ConstraintType getConstraintType(); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraintValidValues.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraintValidValues.java index a07f681c7d..e7bade9421 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraintValidValues.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraintValidValues.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; @@ -45,7 +44,6 @@ public class ToscaPropertyConstraintValidValues implements ToscaPropertyConstrai if ("validValues".equals(attributeName)) { return "valid_values"; } - return attributeName; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationship.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationship.java index 49286ca0e2..91b9869588 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationship.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationship.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.Map; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationshipTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationshipTemplate.java index f42effab6b..1ef3cfd7df 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationshipTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationshipTemplate.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.Map; 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 c8e0527191..79cbb5daf0 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; @@ -29,5 +28,4 @@ import lombok.Setter; public class ToscaRequirement extends ToscaTemplateRequirement { private List occurrences; - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaSchemaDefinition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaSchemaDefinition.java index d02e9da6bd..a88f82c871 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaSchemaDefinition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaSchemaDefinition.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import lombok.Getter; @@ -26,6 +25,7 @@ import lombok.Setter; @Getter @Setter public class ToscaSchemaDefinition { + private String type; private String description; } 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 7fc60d1b5d..f60b22cd69 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; @@ -43,6 +42,4 @@ public class ToscaTemplate { public ToscaTemplate(final String toscaDefinitionsVersion) { this.tosca_definitions_version = toscaDefinitionsVersion; } - } - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateArtifact.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateArtifact.java index 58432ba29b..894a806de0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateArtifact.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateArtifact.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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import lombok.Getter; @@ -29,5 +28,4 @@ public class ToscaTemplateArtifact { private String file; private String type; - } 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 4ec457a6ff..2375af7741 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 @@ -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. @@ -17,13 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.List; import java.util.Map; public class ToscaTemplateCapability { + private List validSourceTypes; private Map properties; @@ -42,5 +42,4 @@ public class ToscaTemplateCapability { 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 85d01e1469..ffbf28b013 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import lombok.Getter; @@ -27,6 +26,7 @@ import org.openecomp.sdc.exception.InvalidArgumentException; @Getter @Setter public class ToscaTemplateRequirement { + private String capability; private String node; private Object relationship; @@ -49,22 +49,22 @@ public class ToscaTemplateRequirement { return; } if (!(relationship instanceof ToscaRelationship) && !(relationship instanceof String)) { - throw new InvalidArgumentException(String.format("relationship %s type not expected. " - + "Supported types are %s and %s", relationship.getClass(), ToscaRelationship.class, String.class)); + throw new InvalidArgumentException(String + .format("relationship %s type not expected. " + "Supported types are %s and %s", relationship.getClass(), ToscaRelationship.class, + String.class)); } this.relationship = relationship; } /** * Checks if the relationship entry is a complex type ({@link ToscaRelationship}). - * - * The relationship can be a simple notation (string) (see Tosca 1.3, Section 3.7.3.2.2), or a multi-line grammar - * notation (complex) (see Tosca 1.3, Section 3.7.3.2.3). + *

+ * The relationship can be a simple notation (string) (see Tosca 1.3, Section 3.7.3.2.2), or a multi-line grammar notation (complex) (see Tosca + * 1.3, Section 3.7.3.2.3). * * @return {@code true} if the relationship is a complex type, {@code false} otherwise */ public boolean isRelationshipComplexNotation() { return relationship instanceof ToscaRelationship; } - } 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 3cecbc2871..a2dc5091e9 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; import java.util.HashMap; 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 198e233fde..2c67f3e72e 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.model; public class VfModuleToscaMetadata implements IToscaMetadata { @@ -71,5 +70,4 @@ public class VfModuleToscaMetadata implements IToscaMetadata { 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 index 1d40de3400..b668ae7efc 100644 --- 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 @@ -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. @@ -17,10 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.utils; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; @@ -33,39 +40,26 @@ import org.openecomp.sdc.be.tosca.CapabilityRequirementConverter; import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - /** * @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 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, CapabilityRequirementConverter capabiltyRequirementConvertor, Map originComponents, ToscaOperationFacade toscaOperationFacade) { + public static void addForwardingPaths(Service service, Map nodeTemplates, + CapabilityRequirementConverter capabiltyRequirementConvertor, Map originComponents, + ToscaOperationFacade toscaOperationFacade) { for (String forwardingPathName : service.getForwardingPaths().keySet()) { - ToscaNodeTemplate forwardingPathNodeTemplate = - new ToscaNodeTemplate(); - final ForwardingPathDataDefinition path = - service.getForwardingPaths().get(forwardingPathName); + ToscaNodeTemplate forwardingPathNodeTemplate = new ToscaNodeTemplate(); + final ForwardingPathDataDefinition path = service.getForwardingPaths().get(forwardingPathName); forwardingPathNodeTemplate.setType(path.getToscaResourceName()); - if (Objects.nonNull(path.getDescription())) { - forwardingPathNodeTemplate.setDescription(path - .getDescription()); + forwardingPathNodeTemplate.setDescription(path.getDescription()); } Map props = new HashMap<>(); if (Objects.nonNull(path.getDestinationPortNumber())) { @@ -77,31 +71,29 @@ public class ForwardingPathToscaUtil { if (MapUtils.isNotEmpty(props)) { forwardingPathNodeTemplate.setProperties(props); } - - final List pathElements = - path.getPathElements() - .getListToscaDataDefinition(); - forwardingPathNodeTemplate.setRequirements(convertPathElementsToRequirements(pathElements, - service, capabiltyRequirementConvertor, originComponents, toscaOperationFacade)); - + 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, CapabilityRequirementConverter capabiltyRequirementConvertor, Map originComponents, ToscaOperationFacade toscaOperationFacade) { + List pathElements, Service service, CapabilityRequirementConverter 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()))); - } - } + 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) { @@ -112,40 +104,38 @@ public class ForwardingPathToscaUtil { } } - - private static Map handleSingleReq( - String fromCP, String fromNode) { + 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, CapabilityRequirementConverter capabiltyRequirementConvertor, Map originComponents, ToscaOperationFacade toscaOperationFacade) { + private static String fetchCPName(Service service, String nodeID, String cpName, CapabilityRequirementConverter capabiltyRequirementConvertor, + Map originComponents, ToscaOperationFacade toscaOperationFacade) { Optional componentInstance = service.getComponentInstanceByName(nodeID); ComponentInstance componentInstanceVal = componentInstance.get(); String name = componentInstanceVal.getNormalizedName(); Component component = originComponents.get(componentInstanceVal.getComponentUid()); - if(componentInstanceVal.getIsProxy()){ + 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(Collection::stream) - .filter(capabilityDefinition -> capabilityDefinition.getName().equals(cpName)).findAny().get(); + .filter(capabilityDefinition -> capabilityDefinition.getName().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(), null); + Either stringBooleanEither = capabiltyRequirementConvertor + .buildSubstitutedName(originComponents, component, reducedPath, capability.getName(), null); return name + "." + stringBooleanEither.left().value(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.java index 475627b827..55de9e5028 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.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. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.utils; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.datatypes.elements.Annotation; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.InputDefinition; @@ -29,16 +31,13 @@ import org.openecomp.sdc.be.tosca.model.ToscaAnnotation; import org.openecomp.sdc.be.tosca.model.ToscaInput; import org.openecomp.sdc.be.tosca.model.ToscaProperty; import org.openecomp.sdc.common.log.wrappers.Logger; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; @org.springframework.stereotype.Component public class InputConverter { - private PropertyConvertor propertyConvertor; + private static final Logger log = Logger.getLogger(ToscaExportHandler.class); + private PropertyConvertor propertyConvertor; @Autowired public InputConverter(PropertyConvertor propertyConvertor) { @@ -56,15 +55,13 @@ public class InputConverter { * type * description * list of properties */ - public Map convertInputs( List inputDef,Map dataTypes) { + public Map convertInputs(List inputDef, Map dataTypes) { log.debug("convert inputs to to tosca "); - Map inputs = new HashMap<>(); if (inputDef != null) { inputDef.forEach(i -> { //Extract input the same as property - ToscaProperty toscaProperty = propertyConvertor.convertProperty(dataTypes, i, - PropertyConvertor.PropertyType.INPUT); + ToscaProperty toscaProperty = propertyConvertor.convertProperty(dataTypes, i, PropertyConvertor.PropertyType.INPUT); //now that we have Tosca property we create new object called tosca input which drives from it ToscaInput toscaInput = new ToscaInput(toscaProperty); List annotations = i.getAnnotations(); @@ -88,7 +85,7 @@ public class InputConverter { if (inputAnnotation.getProperties() != null) { Map properties = new HashMap<>(); inputAnnotation.getProperties().forEach(k -> { - propertyConvertor.convertAndAddValue(dataTypes,properties,k, k::getValue); + propertyConvertor.convertAndAddValue(dataTypes, properties, k, k::getValue); }); annotation.setProperties(properties); } @@ -97,6 +94,3 @@ public class InputConverter { } } } - - - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfaceTypesNameUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfaceTypesNameUtil.java index eda8cef250..d2c0693d56 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfaceTypesNameUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfaceTypesNameUtil.java @@ -16,18 +16,16 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.utils; public class InterfaceTypesNameUtil { private InterfaceTypesNameUtil() { - } /** - * Build the short name of an interface_type by grabbing the final name in its path. E.g. - * "tosca.interfaces.relationship.Configure" will be shortened to "Configure". + * Build the short name of an interface_type by grabbing the final name in its path. E.g. "tosca.interfaces.relationship.Configure" will be + * shortened to "Configure". * * @param interfaceName the full interface name * @return the shortened name of the interface @@ -39,5 +37,4 @@ public class InterfaceTypesNameUtil { final int index = interfaceName.lastIndexOf('.'); return index > 0 && interfaceName.length() > index + 1 ? interfaceName.substring(index + 1) : interfaceName; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/NodeFilterConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/NodeFilterConverter.java index 3ad50229f4..cd1a1c6a55 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/NodeFilterConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/NodeFilterConverter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.tosca.utils; import java.util.ArrayList; @@ -30,7 +29,6 @@ import org.openecomp.sdc.be.ui.model.UINodeFilter; public class NodeFilterConverter { - public Map convertDataMapToUI(Map inMap) { return inMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, o -> convertToUi(o.getValue()))); } @@ -38,39 +36,29 @@ public class NodeFilterConverter { public UINodeFilter convertToUi(final CINodeFilterDataDefinition inNodeFilter) { final UINodeFilter uiNodeFilter = new UINodeFilter(); final ConstraintConvertor constraintConvertor = new ConstraintConvertor(); - final ListDataDefinition nodeFilterProperties = - inNodeFilter.getProperties(); + final ListDataDefinition nodeFilterProperties = inNodeFilter.getProperties(); if (nodeFilterProperties != null && !nodeFilterProperties.isEmpty()) { - final List propertiesConstraint = nodeFilterProperties.getListToscaDataDefinition() - .stream() - .map(property -> property.getConstraints().iterator().next()) - .map(constraintConvertor::convert) - .collect(Collectors.toList()); + final List propertiesConstraint = nodeFilterProperties.getListToscaDataDefinition().stream() + .map(property -> property.getConstraints().iterator().next()).map(constraintConvertor::convert).collect(Collectors.toList()); uiNodeFilter.setProperties(propertiesConstraint); } - final ListDataDefinition nodeFilterCapabilities = - inNodeFilter.getCapabilities(); + final ListDataDefinition nodeFilterCapabilities = inNodeFilter.getCapabilities(); if (nodeFilterCapabilities != null && !nodeFilterCapabilities.isEmpty()) { final List capabilitiesConstraint = new ArrayList<>(); - nodeFilterCapabilities.getListToscaDataDefinition() - .forEach(requirementNodeFilterCapabilityDataDefinition -> - convertCapabilityConstraint(requirementNodeFilterCapabilityDataDefinition, capabilitiesConstraint )); - + nodeFilterCapabilities.getListToscaDataDefinition().forEach( + requirementNodeFilterCapabilityDataDefinition -> convertCapabilityConstraint(requirementNodeFilterCapabilityDataDefinition, + capabilitiesConstraint)); uiNodeFilter.setCapabilities(capabilitiesConstraint); } - return uiNodeFilter; } - private void convertCapabilityConstraint( - final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition, - final List capabilitiesConstraint) { - + private void convertCapabilityConstraint(final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition, + final List capabilitiesConstraint) { final UIConstraint uiConstraint = new UIConstraint(); final ConstraintConvertor constraintConvertor = new ConstraintConvertor(); uiConstraint.setCapabilityName(requirementNodeFilterCapabilityDataDefinition.getName()); - requirementNodeFilterCapabilityDataDefinition.getProperties().getListToscaDataDefinition() - .forEach(property -> capabilitiesConstraint.add(constraintConvertor - .getUiConstraint(property.getConstraints().iterator().next(), uiConstraint))); + requirementNodeFilterCapabilityDataDefinition.getProperties().getListToscaDataDefinition().forEach( + property -> capabilitiesConstraint.add(constraintConvertor.getUiConstraint(property.getConstraints().iterator().next(), uiConstraint))); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OperationArtifactUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OperationArtifactUtil.java index f6a76919f6..3a8bf438f5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OperationArtifactUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OperationArtifactUtil.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.tosca.utils; import java.io.File; @@ -49,31 +48,28 @@ public class OperationArtifactUtil { } /** - * This method assumes that operation.getImplementation() is not NULL ( it should be verified by the caller - * method) + * This method assumes that operation.getImplementation() is not NULL ( it should be verified by the caller method) * * @param operation the specific operation name * @return the full path including file name for operation's artifacts */ - public static String createOperationArtifactPath(Component component, ComponentInstance componentInstance, - OperationDataDefinition operation, boolean isAssociatedComponent) { + public static String createOperationArtifactPath(Component component, ComponentInstance componentInstance, OperationDataDefinition operation, + boolean isAssociatedComponent) { if (!(component instanceof Resource || component instanceof Service)) { return null; } - if (isAssociatedComponent) { // Service Proxy is only in Node Template interface if (componentInstance != null) { - return createOperationArtifactPathInService(componentInstance.getToscaComponentName() - + "_v" + componentInstance.getComponentVersion(), operation); + return createOperationArtifactPathInService( + componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(), operation); } // Resource Instance is part of Node Type interface else { - ResourceMetadataDataDefinition resourceMetadataDataDefinition = - (ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() - .getMetadataDataDefinition(); - return createOperationArtifactPathInService(resourceMetadataDataDefinition.getToscaResourceName() - + "_v" + component.getVersion(), operation); + ResourceMetadataDataDefinition resourceMetadataDataDefinition = (ResourceMetadataDataDefinition) component + .getComponentMetadataDefinition().getMetadataDataDefinition(); + return createOperationArtifactPathInService(resourceMetadataDataDefinition.getToscaResourceName() + "_v" + component.getVersion(), + operation); } } return createOperationArtifactPathInComponent(operation); @@ -82,40 +78,34 @@ public class OperationArtifactUtil { private static String createOperationArtifactPathInComponent(OperationDataDefinition operation) { final String implementationArtifactName = operation.getImplementation().getArtifactName(); if (artifactNameIsALiteralValue(implementationArtifactName)) { - return implementationArtifactName.substring(1, implementationArtifactName.length()-1); + return implementationArtifactName.substring(1, implementationArtifactName.length() - 1); } else { - return CsarUtils.ARTIFACTS + File.separator + WordUtils - .capitalizeFully(ArtifactGroupTypeEnum.DEPLOYMENT.name()) - + File.separator + ArtifactTypeEnum.WORKFLOW.getType() + File.separator + BPMN_ARTIFACT_PATH - + File.separator + implementationArtifactName; + return CsarUtils.ARTIFACTS + File.separator + WordUtils.capitalizeFully(ArtifactGroupTypeEnum.DEPLOYMENT.name()) + File.separator + + ArtifactTypeEnum.WORKFLOW.getType() + File.separator + BPMN_ARTIFACT_PATH + File.separator + implementationArtifactName; } } public static boolean artifactNameIsALiteralValue(final String artifactName) { - return (artifactName.startsWith(Constants.QUOTE) || artifactName.startsWith(Constants.ESCAPED_DOUBLE_QUOTE)) - && (artifactName.endsWith(Constants.QUOTE) || artifactName.endsWith(Constants.ESCAPED_DOUBLE_QUOTE)); + return (artifactName.startsWith(Constants.QUOTE) || artifactName.startsWith(Constants.ESCAPED_DOUBLE_QUOTE)) && ( + artifactName.endsWith(Constants.QUOTE) || artifactName.endsWith(Constants.ESCAPED_DOUBLE_QUOTE)); } - private static String createOperationArtifactPathInService(String toscaComponentName, - OperationDataDefinition operation) { - return CsarUtils.ARTIFACTS + File.separator + toscaComponentName + File.separator + - WordUtils.capitalizeFully(ArtifactGroupTypeEnum.DEPLOYMENT.name()) + File.separator + - ArtifactTypeEnum.WORKFLOW.getType() + File.separator + BPMN_ARTIFACT_PATH + File.separator + - operation.getImplementation().getArtifactName(); + private static String createOperationArtifactPathInService(String toscaComponentName, OperationDataDefinition operation) { + return CsarUtils.ARTIFACTS + File.separator + toscaComponentName + File.separator + WordUtils + .capitalizeFully(ArtifactGroupTypeEnum.DEPLOYMENT.name()) + File.separator + ArtifactTypeEnum.WORKFLOW.getType() + File.separator + + BPMN_ARTIFACT_PATH + File.separator + operation.getImplementation().getArtifactName(); } - public static Map getDistinctInterfaceOperationArtifactsByName( - Component originComponent) { + public static Map getDistinctInterfaceOperationArtifactsByName(Component originComponent) { Map distinctInterfaceArtifactsByName = new HashMap<>(); Map interfaces = originComponent.getInterfaces(); if (MapUtils.isEmpty(interfaces)) { return distinctInterfaceArtifactsByName; } Map interfaceArtifacts = interfaces.values().stream() - .flatMap(interfaceDefinition -> interfaceDefinition.getOperationsMap().values().stream()) - .map(Operation::getImplementationArtifact).filter(Objects::nonNull) - .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, - artifactDefinition -> artifactDefinition, (a1, a2) -> a1)); + .flatMap(interfaceDefinition -> interfaceDefinition.getOperationsMap().values().stream()).map(Operation::getImplementationArtifact) + .filter(Objects::nonNull) + .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, artifactDefinition -> artifactDefinition, (a1, a2) -> a1)); if (MapUtils.isNotEmpty(interfaceArtifacts)) { Set artifactNameSet = new HashSet<>(); for (Map.Entry interfaceArtifactEntry : interfaceArtifacts.entrySet()) { @@ -123,13 +113,10 @@ public class OperationArtifactUtil { if (artifactNameSet.contains(artifactName)) { continue; } - distinctInterfaceArtifactsByName.put(interfaceArtifactEntry.getKey(), - interfaceArtifactEntry.getValue()); + distinctInterfaceArtifactsByName.put(interfaceArtifactEntry.getKey(), interfaceArtifactEntry.getValue()); artifactNameSet.add(artifactName); } - } return distinctInterfaceArtifactsByName; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OutputConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OutputConverter.java index 1e7fc81a3b..8f92034b77 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OutputConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OutputConverter.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.utils; import java.util.Collections; @@ -45,8 +44,8 @@ public class OutputConverter { this.attributeConverterProvider = attributeConverterProvider; } - public Map convert(final List outputDefinitionList, - final Map dataTypes) throws ToscaConversionException { + public Map convert(final List outputDefinitionList, final Map dataTypes) + throws ToscaConversionException { final AttributeConverter attributeConverter = this.attributeConverterProvider.getObject(dataTypes); final Map outputMap = new HashMap<>(); if (CollectionUtils.isEmpty(outputDefinitionList)) { @@ -60,6 +59,3 @@ public class OutputConverter { return outputMap; } } - - - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/SubstitutionFilterConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/SubstitutionFilterConverter.java index d43ba4334c..c083099629 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/SubstitutionFilterConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/SubstitutionFilterConverter.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.tosca.utils; import java.util.Collections; @@ -40,47 +39,35 @@ public class SubstitutionFilterConverter { if (!uiPropertyFilters.isEmpty()) { uiNodeFilter.setProperties(uiPropertyFilters); } - - final List uiCapabilityFilters = - extractCapabilitiesFilter(inSubstitutionFilter, constraintConvertor); + final List uiCapabilityFilters = extractCapabilitiesFilter(inSubstitutionFilter, constraintConvertor); if (!uiCapabilityFilters.isEmpty()) { uiNodeFilter.setCapabilities(uiCapabilityFilters); } - return uiNodeFilter; } private List extractPropertyFilter(final SubstitutionFilterDataDefinition substitutionFilter, final ConstraintConvertor constraintConvertor) { - final ListDataDefinition substitutionFilterProperties = - substitutionFilter.getProperties(); - if (substitutionFilterProperties != null && !substitutionFilterProperties.isEmpty() - && CollectionUtils.isNotEmpty(substitutionFilterProperties.getListToscaDataDefinition())) { - return substitutionFilterProperties.getListToscaDataDefinition() - .stream() - .map(property -> property.getConstraints().iterator().next()) - .map(constraintConvertor::convert) - .collect(Collectors.toList()); + final ListDataDefinition substitutionFilterProperties = substitutionFilter + .getProperties(); + if (substitutionFilterProperties != null && !substitutionFilterProperties.isEmpty() && CollectionUtils + .isNotEmpty(substitutionFilterProperties.getListToscaDataDefinition())) { + return substitutionFilterProperties.getListToscaDataDefinition().stream().map(property -> property.getConstraints().iterator().next()) + .map(constraintConvertor::convert).collect(Collectors.toList()); } - return Collections.emptyList(); } private List extractCapabilitiesFilter(final SubstitutionFilterDataDefinition substitutionFilter, final ConstraintConvertor constraintConvertor) { - final ListDataDefinition substitutionFilterCapabilities = - substitutionFilter.getCapabilities(); - if (substitutionFilterCapabilities != null && !substitutionFilterCapabilities.isEmpty() - && CollectionUtils.isNotEmpty(substitutionFilterCapabilities.getListToscaDataDefinition())) { - return substitutionFilterCapabilities - .getListToscaDataDefinition() - .stream() + final ListDataDefinition substitutionFilterCapabilities = substitutionFilter + .getCapabilities(); + if (substitutionFilterCapabilities != null && !substitutionFilterCapabilities.isEmpty() && CollectionUtils + .isNotEmpty(substitutionFilterCapabilities.getListToscaDataDefinition())) { + return substitutionFilterCapabilities.getListToscaDataDefinition().stream() .map(capabilities -> capabilities.getProperties().getListToscaDataDefinition().iterator().next()) - .map(property -> property.getConstraints().iterator().next()) - .map(constraintConvertor::convert) - .collect(Collectors.toList()); + .map(property -> property.getConstraints().iterator().next()).map(constraintConvertor::convert).collect(Collectors.toList()); } - return Collections.emptyList(); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionData.java index 5e97ac67f4..51b36538e5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionData.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionData.java @@ -13,44 +13,44 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.types; public class ServiceConsumptionData { - private String inputId; - private String source; - private String value; - private String type; - - public String getInputId() { - return inputId; - } - - public void setInputId(String inputId) { - this.inputId = inputId; - } - - public String getSource() { - return source; - } - - public void setSource(String source) { - this.source = source; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } + + private String inputId; + private String source; + private String value; + private String type; + + public String getInputId() { + return inputId; + } + + public void setInputId(String inputId) { + this.inputId = inputId; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionSource.java b/catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionSource.java index 9e297b7c45..bd6ae1eb85 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionSource.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionSource.java @@ -13,37 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.be.types; import java.util.HashMap; import java.util.Map; -public enum ServiceConsumptionSource { - SERVICE_INPUT("ServiceInput"), - STATIC("Static"); - - - private static Map sourceToValue; +public enum ServiceConsumptionSource { + SERVICE_INPUT("ServiceInput"), STATIC("Static"); + private static Map sourceToValue; - static { - sourceToValue = new HashMap<>(); - for(ServiceConsumptionSource sourceName : ServiceConsumptionSource.values()) { - sourceToValue.put(sourceName.source, sourceName); + static { + sourceToValue = new HashMap<>(); + for (ServiceConsumptionSource sourceName : ServiceConsumptionSource.values()) { + sourceToValue.put(sourceName.source, sourceName); + } } - } - private String source; + private String source; - ServiceConsumptionSource(String source) { - this.source = source; - } + ServiceConsumptionSource(String source) { + this.source = source; + } - public static ServiceConsumptionSource getSourceValue(String source) { - return sourceToValue.get(source); - } + public static ServiceConsumptionSource getSourceValue(String source) { + return sourceToValue.get(source); + } - public String getSource() { - return source; - } + public String getSource() { + return source; + } } 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 c15c063149..4274532e93 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.user; /* @@ -36,7 +35,3 @@ public enum Role { return null; } } - - - - 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 f5b33beb7e..4aa852cf7e 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 @@ -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. @@ -17,11 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.user; public enum UserAdminAction { - 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 589fdd8de4..758ac07b89 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.user; import java.util.regex.Matcher; @@ -25,11 +24,17 @@ import java.util.regex.Pattern; public class 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 USER_ID_PATTERN = "\\w{1,25}"; + private static UserAdminValidator userAdminValidator = null; private Pattern emailPat; private Pattern userIdPat; private Matcher matcher; - private static UserAdminValidator userAdminValidator = null; + private UserAdminValidator() { + emailPat = Pattern.compile(EMAIL_PATTERN); + userIdPat = Pattern.compile(USER_ID_PATTERN); + } public static synchronized UserAdminValidator getInstance() { if (userAdminValidator == null) { @@ -38,15 +43,6 @@ public class 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 USER_ID_PATTERN = "\\w{1,25}"; - - 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(); 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 e1cac1c7ed..f90440011d 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 @@ -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. @@ -17,10 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.user; +import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.ADD_USER; +import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.GET_USERS_LIST; +import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_USER; + import fj.data.Either; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -41,17 +50,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.ADD_USER; -import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.GET_USERS_LIST; -import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_USER; - @org.springframework.stereotype.Component public class UserBusinessLogic { @@ -59,7 +57,6 @@ public class UserBusinessLogic { private static final String IN_CERTIFICATION_CHECKED_OUT = "in-certification/checked-out"; private static final String UNKNOWN = "UNKNOWN"; private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance(); - private final UserAdminOperation userAdminOperation; private final ComponentsUtils componentsUtils; private final UserOperation facadeUserOperation; @@ -91,7 +88,7 @@ public class UserBusinessLogic { handleUserAccessAuditing(userId, ActionStatus.USER_NOT_FOUND); throw new ByActionStatusComponentException(ActionStatus.USER_NOT_FOUND, userId); } - if (Objects.isNull(userContext.getUserRoles())){ + if (Objects.isNull(userContext.getUserRoles())) { userContext.setUserRoles(new HashSet<>()); } return convertUserContextToUser(userContext); @@ -110,11 +107,11 @@ public class UserBusinessLogic { public boolean hasActiveUser(String userId) { UserContext userContext = ThreadLocalsHolder.getUserContext(); - if (Objects.isNull(userContext) || Objects.isNull(userContext.getUserId()) ) { + if (Objects.isNull(userContext) || Objects.isNull(userContext.getUserId())) { handleUserAccessAuditing(userId, ActionStatus.USER_NOT_FOUND); return false; } - if (Objects.isNull(userContext.getUserRoles()) || userContext.getUserRoles().isEmpty()){ + if (Objects.isNull(userContext.getUserRoles()) || userContext.getUserRoles().isEmpty()) { handleUserAccessAuditing(userId, ActionStatus.USER_INACTIVE); return false; } @@ -122,25 +119,20 @@ public class UserBusinessLogic { } public User createUser(String modifierUserId, User newUser) { - User modifier = getValidModifier(modifierUserId, newUser.getUserId(), AuditingActionEnum.ADD_USER); - // verify user not exist String newUserId = newUser.getUserId(); Either eitherUserInDB = verifyNewUser(newUserId); newUser.setStatus(UserStatusEnum.ACTIVE); - validateEmail(newUser); - validateRole(newUser); - // handle last login if user is import if (newUser.getLastLoginTime() == null) { newUser.setLastLoginTime(0L); } - User createdUser; - if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right().value())) { // user inactive - update state // exist + if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right() + .value())) { // user inactive - update state // exist newUser.setLastLoginTime(0L); createdUser = userAdminOperation.updateUserData(newUser); } else { // user does not exist - create new user @@ -199,37 +191,32 @@ public class UserBusinessLogic { componentsUtils.auditAdminUserActionAndThrowException(ADD_USER, null, null, null, status, newUserId); } } - return eitherUserInDB; } private Either getUserData(String newUserId) { if (newUserId == null) { - log.error(EcompLoggerErrorCode.DATA_ERROR, "", "","Create user - new user id is missing"); + log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", "Create user - new user id is missing"); throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } - return userAdminOperation.getUserData(newUserId, false); } public User updateUserRole(String modifierUserId, String userIdToUpdate, String userRole) { - User modifier = getValidModifier(modifierUserId, userIdToUpdate, UPDATE_USER); User userToUpdate = getUser(userIdToUpdate, false); validateChangeRoleToAllowedRoles(userRole); - List userPendingTasks = userAdminOperation.getUserPendingTasksList(userToUpdate, getChangeRoleStateLimitations(userToUpdate)); if (!userPendingTasks.isEmpty()) { log.debug("updateUserRole method - User cannot be updated, user have pending projects userId {}", userIdToUpdate); String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')'; - componentsUtils.auditAdminUserActionAndThrowException(UPDATE_USER, modifier, userToUpdate, null, ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, IN_CERTIFICATION_CHECKED_OUT); + componentsUtils.auditAdminUserActionAndThrowException(UPDATE_USER, modifier, userToUpdate, null, + ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, IN_CERTIFICATION_CHECKED_OUT); } - Role newRole = Role.valueOf(userRole); User newUser = new User(); newUser.setRole(newRole.name()); newUser.setUserId(userIdToUpdate); - User updatedUser = userAdminOperation.updateUserData(newUser); handleAuditing(modifier, userToUpdate, updatedUser, componentsUtils.getResponseFormat(ActionStatus.OK), UPDATE_USER); getFacadeUserOperation().updateUserCache(UserOperationEnum.CHANGE_ROLE, updatedUser.getUserId(), updatedUser.getRole()); @@ -238,7 +225,7 @@ public class UserBusinessLogic { private void validateChangeRoleToAllowedRoles(String userRole) { List allowedRoles = Arrays.asList(UserRoleEnum.DESIGNER.getName(), UserRoleEnum.ADMIN.getName()); - if (!allowedRoles.contains(userRole)){ + if (!allowedRoles.contains(userRole)) { throw new ByActionStatusComponentException(ActionStatus.INVALID_ROLE, userRole); } } @@ -248,13 +235,11 @@ public class UserBusinessLogic { log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", "user modifier is missing"); throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } - User modifier = getUser(modifierUserId, false); if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { log.debug("user is not admin. Id = {}", modifier.getUserId()); componentsUtils.auditAdminUserActionAndThrowException(actionEnum, modifier, null, null, ActionStatus.RESTRICTED_OPERATION); } - if (modifier.getUserId().equals(userIdHandle)) { log.debug("admin user cannot act on self. Id = {}", modifier.getUserId()); componentsUtils.auditAdminUserActionAndThrowException(actionEnum, modifier, null, null, ActionStatus.UPDATE_USER_ADMIN_CONFLICT); @@ -302,10 +287,7 @@ public class UserBusinessLogic { handleGetUsersListAuditing(user, responseFormat, rolesStr); return Either.right(responseFormat); } - List users = response.left().value() - .stream() - .filter(u-> StringUtils.isNotEmpty(u.getUserId())) - .collect(Collectors.toList()); + List users = response.left().value().stream().filter(u -> StringUtils.isNotEmpty(u.getUserId())).collect(Collectors.toList()); return Either.left(users); } @@ -331,27 +313,21 @@ public class UserBusinessLogic { log.debug("authorize method - user id is missing"); throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION); } - User user = getUser(userId, false); - String firstName = authUser.getFirstName(); if (firstName != null && !firstName.isEmpty() && !firstName.equals(user.getFirstName())) { user.setFirstName(firstName); } - String lastName = authUser.getLastName(); if (lastName != null && !lastName.isEmpty() && !lastName.equals(user.getLastName())) { user.setLastName(lastName); } - String email = authUser.getEmail(); if (email != null && !email.isEmpty() && !email.equals(user.getEmail())) { user.setEmail(email); } - // last login time stamp handle user.setLastLoginTime(); - User updatedUser = userAdminOperation.updateUserData(user); Long lastLoginTime = user.getLastLoginTime(); if (lastLoginTime != null) { @@ -359,7 +335,6 @@ public class UserBusinessLogic { } else { updatedUser.setLastLoginTime(0L); } - handleUserAccessAuditing(updatedUser.getUserId(), ActionStatus.OK); ASDCKpiApi.countUsersAuthorizations(); return updatedUser; @@ -369,11 +344,8 @@ public class UserBusinessLogic { * 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"); @@ -381,23 +353,19 @@ public class UserBusinessLogic { handleUserAccessAuditing(updatedUserCred, responseFormat); return Either.right(responseFormat); } - User user = getUser(userId, false); String firstName = updatedUserCred.getFirstName(); if (firstName != null && !firstName.isEmpty() && !firstName.equals(user.getFirstName())) { user.setFirstName(firstName); } - String lastName = updatedUserCred.getLastName(); if (lastName != null && !lastName.isEmpty() && !lastName.equals(user.getLastName())) { user.setLastName(lastName); } - String email = updatedUserCred.getEmail(); if (email != null && !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()); @@ -405,7 +373,6 @@ public class UserBusinessLogic { } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) { user.setLastLoginTime(updatedUserCred.getLastLoginTime()); } - User updatedUser = userAdminOperation.updateUserData(user); responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); handleUserAccessAuditing(updatedUser, responseFormat); @@ -432,5 +399,4 @@ public class UserBusinessLogic { public UserOperation getFacadeUserOperation() { return facadeUserOperation; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogicExt.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogicExt.java index 38b4339e7c..345501dc8f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogicExt.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogicExt.java @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.user; import fj.data.Either; +import java.util.ArrayList; +import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; @@ -37,14 +38,10 @@ import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.ArrayList; -import java.util.List; - @org.springframework.stereotype.Component public class UserBusinessLogicExt { private static final Logger log = Logger.getLogger(UserBusinessLogicExt.class); - private final UserBusinessLogic userBusinessLogic; private final UserAdminOperation userAdminOperation; private final LifecycleBusinessLogic lifecycleBusinessLogic; @@ -58,30 +55,27 @@ public class UserBusinessLogicExt { this.componentsUtils = componentsUtils; } - public User deActivateUser(String modifierUserId, String userIdToDeactivate) { - User modifier = userBusinessLogic.getValidModifier(modifierUserId, userIdToDeactivate, AuditingActionEnum.DELETE_USER); - User userToDeactivate = userBusinessLogic.getUser(userIdToDeactivate, false); if (userToDeactivate.getStatus() == UserStatusEnum.INACTIVE) { log.debug("deActivateUser method - User already inactive", userIdToDeactivate); - componentsUtils.auditAdminUserActionAndThrowException(AuditingActionEnum.DELETE_USER, modifier, userToDeactivate, null, ActionStatus.USER_NOT_FOUND, userIdToDeactivate); + componentsUtils + .auditAdminUserActionAndThrowException(AuditingActionEnum.DELETE_USER, modifier, userToDeactivate, null, ActionStatus.USER_NOT_FOUND, + userIdToDeactivate); } - handleTasksInProgress(userToDeactivate); - userAdminOperation.deActivateUser(userToDeactivate); componentsUtils.auditUserAccess(userToDeactivate, ActionStatus.OK); handleAuditing(modifier, userToDeactivate, null, componentsUtils.getResponseFormat(ActionStatus.OK), AuditingActionEnum.DELETE_USER); - userBusinessLogic.getFacadeUserOperation().updateUserCache(UserOperationEnum.DEACTIVATE, userToDeactivate.getUserId(), userToDeactivate.getRole()); + userBusinessLogic.getFacadeUserOperation() + .updateUserCache(UserOperationEnum.DEACTIVATE, userToDeactivate.getUserId(), userToDeactivate.getRole()); return userToDeactivate; } private void handleTasksInProgress(User userToDeactivate) { String userIdToDeactivate = userToDeactivate.getUserId(); - List userPendingTasks = userAdminOperation - .getUserActiveComponents(userToDeactivate, getDeactivateUserStateLimitations()); + List userPendingTasks = userAdminOperation.getUserActiveComponents(userToDeactivate, getDeactivateUserStateLimitations()); if (userPendingTasks.isEmpty()) { return; } @@ -95,17 +89,19 @@ public class UserBusinessLogicExt { log.debug("Erroneous component state when deactivating user for component {} state is {}", componentId, currentState); continue; } - Either result = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), componentId, userToDeactivate, - transition, changeInfo, false, true); + Either result = lifecycleBusinessLogic + .changeComponentState(component.getComponentType(), componentId, userToDeactivate, transition, changeInfo, false, true); if (result.isRight()) { failedComponents.add(component.getName()); } } if (CollectionUtils.isNotEmpty(failedComponents)) { String componentList = failedComponents.toString(); - log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", "User cannot be deleted, {} has the following pending projects that cannot be committed: {}", userIdToDeactivate, componentList); + log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", + "User cannot be deleted, {} has the following pending projects that cannot be committed: {}", userIdToDeactivate, componentList); String userInfo = userToDeactivate.getFirstName() + " " + userToDeactivate.getLastName() + '(' + userToDeactivate.getUserId() + ')'; - componentsUtils.auditAdminUserActionAndThrowException(AuditingActionEnum.DELETE_USER, null, userToDeactivate, null, ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, componentList); + componentsUtils.auditAdminUserActionAndThrowException(AuditingActionEnum.DELETE_USER, null, userToDeactivate, null, + ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, componentList); } } @@ -126,5 +122,4 @@ public class UserBusinessLogicExt { private void handleAuditing(User modifier, User userBefor, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) { componentsUtils.auditAdminUserAction(actionName, modifier, userBefor, userAfter, responseFormat); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserMessage.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserMessage.java index 73943f6c4e..f108a76027 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserMessage.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserMessage.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.user; import lombok.AllArgsConstructor; @@ -31,6 +30,7 @@ import org.openecomp.sdc.be.catalog.api.ITypeMessage; @AllArgsConstructor @ToString public class UserMessage implements ITypeMessage { + private UserOperationEnum operation; private String userId; private String role; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserOperationEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserOperationEnum.java index c4cc62d271..e54a562f1b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserOperationEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserOperationEnum.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.user; public enum UserOperationEnum { 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 index 4be9158a47..0ff6bd6604 100644 --- 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 @@ -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. @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 index d7f07baccb..0f8cbf4182 100644 --- 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 @@ -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. @@ -17,17 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.view; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; - -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; @@ -36,9 +29,15 @@ import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; +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; /** - * 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. + * 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) @@ -55,7 +54,8 @@ public class MixinModelWriter implements MessageBodyWriter { } @Override - public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { + public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); List mixinSourceTargets = getMixinSourceTarget(annotations); @@ -64,19 +64,14 @@ public class MixinModelWriter implements MessageBodyWriter { } 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()); + 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))); + 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 index 35ae05b82f..4df20e9837 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.view; /** 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 index 823a6f74c7..4f91957d7e 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.view; import java.lang.annotation.ElementType; @@ -30,10 +29,9 @@ import java.lang.annotation.Target; @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 index 00006e0ebf..b9e365caec 100644 --- 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 @@ -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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.view; import java.lang.annotation.ElementType; @@ -28,10 +27,10 @@ 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. + * 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/config/CatalogBESpringConfig.java b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java index 52a1023062..570cabee5f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java @@ -40,8 +40,10 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; +// @formatter:off @Configuration -@ComponentScan({"org.openecomp.sdc.be.user", +@ComponentScan({ + "org.openecomp.sdc.be.user", "org.openecomp.sdc.be.facade.operations", "org.openecomp.sdc.be.impl", "org.openecomp.sdc.be.auditing.impl", @@ -63,8 +65,8 @@ import org.springframework.core.annotation.Order; "org.openecomp.sdc.be.servlets", "org.openecomp.sdc.be.filters", "org.openecomp.sdc.be.plugins", - "org.openecomp.sdc.be.togglz" -}) + "org.openecomp.sdc.be.togglz"}) +// @formatter:on public class CatalogBESpringConfig { private static final int BEFORE_TRANSACTION_MANAGER = 0; @@ -97,7 +99,9 @@ public class CatalogBESpringConfig { } @Bean - public RoleAuthorizationHandler roleAuthorizationHandler() {return new RoleAuthorizationHandler();} + public RoleAuthorizationHandler roleAuthorizationHandler() { + return new RoleAuthorizationHandler(); + } @Bean public CloseableHttpClient httpClientConnectionManager() { @@ -106,13 +110,19 @@ public class CatalogBESpringConfig { } @Bean - public PortalConfiguration portalConfiguration() throws CipherUtilException {return new PortalConfiguration();} + public PortalConfiguration portalConfiguration() throws CipherUtilException { + return new PortalConfiguration(); + } @Bean - public FilterConfiguration filterConfiguration() {return new FilterConfiguration(configuration());} + public FilterConfiguration filterConfiguration() { + return new FilterConfiguration(configuration()); + } @Bean - public ThreadLocalUtils threadLocalUtils() {return new ThreadLocalUtils();} + public ThreadLocalUtils threadLocalUtils() { + return new ThreadLocalUtils(); + } @Bean public PortalClient portalClient() throws CipherUtilException { @@ -120,8 +130,7 @@ public class CatalogBESpringConfig { } @Bean - public org.openecomp.sdc.be.config.Configuration configuration(){ + public org.openecomp.sdc.be.config.Configuration configuration() { return ConfigurationManager.getConfigurationManager().getConfiguration(); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/config/HttpClientFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/config/HttpClientFactory.java index f2544aa7ef..176f05a25c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/config/HttpClientFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/config/HttpClientFactory.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.config; import org.apache.http.client.HttpRequestRetryHandler; @@ -46,28 +45,19 @@ public class HttpClientFactory { private static final int DEFAULT_MAX_CONNECTION_PER_ROUTE = 5; private static final int VALIDATE_CONNECTION_AFTER_INACTIVITY_MS = 10000; private static final int CONNECT_TIMEOUT_MS = 15000; - private static final Logger log = Logger.getLogger(HttpClientFactory.class); private static final UserTokenHandler userTokenHandler = context -> null; - private HttpClientConnectionManager createConnectionManager(){ + private HttpClientConnectionManager createConnectionManager() { SSLConnectionSocketFactory sslsf = getSslConnectionSocketFactory(); - Registry registry = RegistryBuilder.create() - .register(Constants.HTTP, PlainConnectionSocketFactory.getSocketFactory()) - .register(Constants.HTTPS, sslsf).build(); - + .register(Constants.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(Constants.HTTPS, sslsf).build(); PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry); - manager.setMaxTotal(DEFAULT_CONNECTION_POOL_SIZE); manager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTION_PER_ROUTE); manager.setValidateAfterInactivity(VALIDATE_CONNECTION_AFTER_INACTIVITY_MS); - - SocketConfig socketConfig = SocketConfig.custom() - .setSoTimeout(CONNECT_TIMEOUT_MS) - .build(); + SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(CONNECT_TIMEOUT_MS).build(); manager.setDefaultSocketConfig(socketConfig); - return manager; } @@ -75,7 +65,6 @@ public class HttpClientFactory { return new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()); } - /* The difference between this client factory and the one in common api, is that this one returns an apache httpclient instance, rather than a custom created custom. @@ -87,24 +76,16 @@ public class HttpClientFactory { HttpClientConfig httpClientConfig = new HttpClientConfig(new Timeouts(connectTimeoutMs, readTimeoutMs)); HttpClientConfigImmutable immutableHttpClientConfig = new HttpClientConfigImmutable(httpClientConfig); RequestConfig requestConfig = createClientTimeoutConfiguration(immutableHttpClientConfig); - return HttpClients.custom() - .setConnectionManager(connManager) - .setDefaultRequestConfig(requestConfig) - .setUserTokenHandler(userTokenHandler) - .setRetryHandler(resolveRetryHandler(immutableHttpClientConfig)) - .build(); + return HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(requestConfig).setUserTokenHandler(userTokenHandler) + .setRetryHandler(resolveRetryHandler(immutableHttpClientConfig)).build(); } - private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) { - return RequestConfig.custom() - .setConnectTimeout(config.getConnectTimeoutMs()) - .setSocketTimeout(config.getReadTimeoutMs()) - .setConnectionRequestTimeout(config.getConnectPoolTimeoutMs()) - .build(); + private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) { + return RequestConfig.custom().setConnectTimeout(config.getConnectTimeoutMs()).setSocketTimeout(config.getReadTimeoutMs()) + .setConnectionRequestTimeout(config.getConnectPoolTimeoutMs()).build(); } private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) { return config.getNumOfRetries() > 0 ? config.getRetryHandler() : null; } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/config/ObjectMapperProvider.java b/catalog-be/src/main/java/org/openecomp/sdc/config/ObjectMapperProvider.java index 8b5f7ed6f2..62c4d90799 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/config/ObjectMapperProvider.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/config/ObjectMapperProvider.java @@ -17,12 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.config; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; - import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; @@ -39,9 +37,8 @@ public class ObjectMapperProvider implements ContextResolver { } private ObjectMapper createObjectMapper() { - return new ObjectMapper() - .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); + return new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); } @Override diff --git a/catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java index e6d12c9b4c..6ada3005d5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java @@ -13,13 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.externalupload.utils; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableSet; -import org.apache.commons.beanutils.BeanUtils; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; @@ -29,72 +26,64 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import org.apache.commons.beanutils.BeanUtils; public class ServiceUtils { - private static ImmutableSet collectionClasses = ImmutableSet.of(Map.class, List.class, Set.class); - private static ImmutableSet primitiveTypesClasses = ImmutableSet.of(String.class, Integer.class, Double.class, Float.class); + private static ImmutableSet collectionClasses = ImmutableSet.of(Map.class, List.class, Set.class); + private static ImmutableSet primitiveTypesClasses = ImmutableSet.of(String.class, Integer.class, Double.class, Float.class); - private ServiceUtils() {} - - public static Optional createObjectUsingSetters(Object objectCandidate, - Class classToCreate) - throws Exception { - if (Objects.isNull(objectCandidate)) { - return Optional.empty(); + private ServiceUtils() { } - Map objectAsMap = getObjectAsMap(objectCandidate); - T result = classToCreate.newInstance(); - - List declaredFields = getAllFields(classToCreate); - for( Field field : declaredFields){ - if(isComplexClass(field)){ - Optional objectUsingSetters = - createObjectUsingSetters(objectAsMap.get(field.getName()), field.getType()); - if( objectUsingSetters.isPresent()){ - objectAsMap.remove(field.getName()); - objectAsMap.put(field.getName(), objectUsingSetters.get()); + public static Optional createObjectUsingSetters(Object objectCandidate, Class classToCreate) throws Exception { + if (Objects.isNull(objectCandidate)) { + return Optional.empty(); } - } + Map objectAsMap = getObjectAsMap(objectCandidate); + T result = classToCreate.newInstance(); + List declaredFields = getAllFields(classToCreate); + for (Field field : declaredFields) { + if (isComplexClass(field)) { + Optional objectUsingSetters = createObjectUsingSetters(objectAsMap.get(field.getName()), field.getType()); + if (objectUsingSetters.isPresent()) { + objectAsMap.remove(field.getName()); + objectAsMap.put(field.getName(), objectUsingSetters.get()); + } + } + } + BeanUtils.populate(result, objectAsMap); + return Optional.of(result); } - BeanUtils.populate(result, objectAsMap); - - return Optional.of(result); - } - private static List getAllFields(Class clazz) { - List fields = new ArrayList<>(); - for(Class c = clazz; c != null; c = c.getSuperclass()) { - fields.addAll(Arrays.asList(c.getDeclaredFields())); + private static List getAllFields(Class clazz) { + List fields = new ArrayList<>(); + for (Class c = clazz; c != null; c = c.getSuperclass()) { + fields.addAll(Arrays.asList(c.getDeclaredFields())); + } + return fields; } - return fields; - } - - private static boolean isComplexClass(Field field) { - return !isCollectionClass(field) - && !isPrimitiveClass(field) - && !field.getType().equals(Object.class); - } - - private static boolean isCollectionClass(Field field) { - return collectionClasses.contains(field.getType()); - } + private static boolean isComplexClass(Field field) { + return !isCollectionClass(field) && !isPrimitiveClass(field) && !field.getType().equals(Object.class); + } - private static boolean isPrimitiveClass(Field field) { - return primitiveTypesClasses.contains(field.getType()); - } + private static boolean isCollectionClass(Field field) { + return collectionClasses.contains(field.getType()); + } - public static Map getObjectAsMap(Object obj) { - return new ObjectMapper().convertValue(obj, Map.class); - } + private static boolean isPrimitiveClass(Field field) { + return primitiveTypesClasses.contains(field.getType()); + } - public static Set getClassFieldNames(Class classType) { - Set fieldNames = new HashSet<>(); - List allFields = getAllFields(classType); - allFields.forEach(field -> fieldNames.add(field.getName())); + public static Map getObjectAsMap(Object obj) { + return new ObjectMapper().convertValue(obj, Map.class); + } - return fieldNames; - } -} \ No newline at end of file + public static Set getClassFieldNames(Class classType) { + Set fieldNames = new HashSet<>(); + List allFields = getAllFields(classType); + allFields.forEach(field -> fieldNames.add(field.getName())); + return fieldNames; + } +} -- cgit 1.2.3-korg